package com.fintech.third.service.moxie;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fintech.common.enums.RespStatus;
import com.fintech.common.service.BaseServiceImpl;
import com.fintech.common.util.ApiResponse;
import com.fintech.common.util.ProductUtils;
import com.fintech.common.util.PropertiesUtils;
import com.fintech.datagroud.dao.moxie.IntMxAlipayUserInfoMapper;
import com.fintech.datagroud.dao.moxie.IntMxCallDetailsMapper;
import com.fintech.datagroud.dao.moxie.IntMxMobileAuthenticationMapper;
import com.fintech.datagroud.dao.moxie.IntMxUserBasicInfoMapper;
import com.fintech.datagroud.entity.moxie.IntMxMobileAuthentication;
import com.fintech.datagroud.service.DGMoXieService;
import com.fintech.third.constant.LocalStatus;
import com.fintech.third.constant.ParamName;
import com.fintech.third.constant.ThirdMethodConstants;
import com.fintech.third.constant.ThirdProductChannelConstant;
import com.fintech.third.dao.EdcDataQueryLogMapper;
import com.fintech.third.dao.MoxieTaskInfoMapper;
import com.fintech.third.dao.moxie.MoXieDataInfoMapper;
import com.fintech.third.model.EdcDataQueryLog;
import com.fintech.third.model.MoxieTaskInfo;
import com.fintech.third.model.ThirdProperties;
import com.fintech.third.model.moxie.AuthToken;
import com.fintech.third.model.moxie.MoXieTaskResult;
import com.fintech.third.model.moxie.MoXieTaskType;
import com.fintech.third.model.moxie.MoxieResponse;
import com.fintech.third.model.moxie.RealNameAuthentication;
import com.fintech.third.model.moxie.alipay.MXAlipayReport;
import com.fintech.third.model.moxie.alipay.MXAlipayZmsReport;
import com.fintech.third.model.moxie.carries.AllDataDetails;
import com.fintech.third.model.moxie.carries.BillDetail;
import com.fintech.third.model.moxie.carries.MXUserReportCall;
import com.fintech.third.model.moxie.carries.MobileBasicV3;
import com.fintech.third.model.moxie.carries.NumberReport;
import com.fintech.third.model.moxie.carries.ShortMessageDetailV2;
import com.fintech.third.model.moxie.carries.VoiceCallDetailList;
import com.fintech.third.model.moxie.carriesv2.MXReport;
import com.fintech.third.model.moxie.chsi.EducationInfoList;
import com.fintech.third.model.moxie.chsi.StudentInfoList;
import com.fintech.third.model.moxie.dataprovide.IntMxAccountBaseInfo;
import com.fintech.third.model.moxie.dataprovide.IntMxActiveDegreeDetail;
import com.fintech.third.model.moxie.dataprovide.IntMxActiveDegress;
import com.fintech.third.model.moxie.dataprovide.IntMxAlipayUserInfo;
import com.fintech.third.model.moxie.dataprovide.IntMxBasicInfoCheckItems;
import com.fintech.third.model.moxie.dataprovide.IntMxBillRecord;
import com.fintech.third.model.moxie.dataprovide.IntMxBillsMonth;
import com.fintech.third.model.moxie.dataprovide.IntMxCallAnalysis;
import com.fintech.third.model.moxie.dataprovide.IntMxCallContactDetail;
import com.fintech.third.model.moxie.dataprovide.IntMxCallDetails;
import com.fintech.third.model.moxie.dataprovide.IntMxCallDurationDetail;
import com.fintech.third.model.moxie.dataprovide.IntMxCallFamilyDetail;
import com.fintech.third.model.moxie.dataprovide.IntMxCallLocal6m;
import com.fintech.third.model.moxie.dataprovide.IntMxCallLocationDetail;
import com.fintech.third.model.moxie.dataprovide.IntMxCallLocationTop3;
import com.fintech.third.model.moxie.dataprovide.IntMxCallMobile6m;
import com.fintech.third.model.moxie.dataprovide.IntMxCallNumTop3;
import com.fintech.third.model.moxie.dataprovide.IntMxCallThirdPartyDetail;
import com.fintech.third.model.moxie.dataprovide.IntMxCallTimeDetail;
import com.fintech.third.model.moxie.dataprovide.IntMxConsumptionAnalysis;
import com.fintech.third.model.moxie.dataprovide.IntMxConsumptionDetail;
import com.fintech.third.model.moxie.dataprovide.IntMxDataSource;
import com.fintech.third.model.moxie.dataprovide.IntMxDataUsageDetails;
import com.fintech.third.model.moxie.dataprovide.IntMxLoanInfo;
import com.fintech.third.model.moxie.dataprovide.IntMxLoanRepayRecord;
import com.fintech.third.model.moxie.dataprovide.IntMxPackageInfo;
import com.fintech.third.model.moxie.dataprovide.IntMxPackageItems;
import com.fintech.third.model.moxie.dataprovide.IntMxRechargeItems;
import com.fintech.third.model.moxie.dataprovide.IntMxRiskAnalysis;
import com.fintech.third.model.moxie.dataprovide.IntMxRiskCheckItem;
import com.fintech.third.model.moxie.dataprovide.IntMxSmsDetails;
import com.fintech.third.model.moxie.dataprovide.IntMxUserBasicInfo;
import com.fintech.third.model.moxie.dataprovide.IntMxUserInfo;
import com.fintech.third.model.moxie.fund.BillRecord;
import com.fintech.third.model.moxie.fund.LoanInfo;
import com.fintech.third.model.moxie.fund.LoanRepayRecord;
import com.fintech.third.model.moxie.fund.UserFundRecord;
import com.fintech.third.model.moxie.fund.UserInfo;
import com.fintech.third.model.moxie.insurance.InsurancePolicy;
import com.fintech.third.model.moxie.mail.EmailBillInstallmentList;
import com.fintech.third.model.moxie.mail.EmailBillList;
import com.fintech.third.model.moxie.mail.EmailBillShoppingSheetList;
import com.fintech.third.service.ThirdDataDeal;
import com.fintech.third.service.moxie.task.TaskCreateReq;
import com.fintech.third.service.moxie.task.TaskCreateRsp;
import com.fintech.third.service.moxie.task.TaskStatusRsp;
import com.fintech.third.service.moxie.task.TaskVoidRsp;
import com.fintech.third.service.moxie.task.UserInput;
import com.fintech.third.utils.DateUtil;
import com.fintech.third.utils.MoXieCarrierForMall;
import com.fintech.third.utils.MoXieCarrierThread;
import com.fintech.third.utils.MoxieFundThread;
import com.fintech.third.utils.SerialNumCreater;
import com.fintech.third.utils.ThirdPropertiesInitUtil;
import com.fintech.third.utils.moxie.MoxieApiFactory;
import com.fintech.third.utils.moxie.ObjectMappers;
import com.marvels.common.utils.MarvelsLogUtil;

import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import retrofit2.Call;
import retrofit2.Response;

@Service("MoXie")
public class MoXieImpl extends BaseServiceImpl implements MoXieService {
	@Autowired
	private EdcDataQueryLogMapper edcDataQueryLogMapper;
	
	private MoxieApiFactory moxieApiFactory;
	
	private MoxieApiFactory getMoxieApiFactory(){
		if(this.moxieApiFactory == null){
			this.moxieApiFactory= MoxieApiFactory.builder().withAuthToken(new AuthToken(ThirdPropertiesInitUtil.getThirdProperties().getMx_api_key(), ThirdPropertiesInitUtil.getThirdProperties().getMx_token()))
					.withBaseUrl(ThirdPropertiesInitUtil.getThirdProperties().getMx_baseUrl()).build();
		}
		return this.moxieApiFactory;
	}
	@Autowired
	private MoXieDataInfoMapper moXieDataInfoMapper;

	@Autowired
	private MoxieTaskInfoMapper moxieTaskInfoMapper;

	@Autowired(required=false)
	private DGMoXieService dGMoXieService;

	@Autowired
	private IntMxMobileAuthenticationMapper intMxMobileAuthenticationMapper;

	@Autowired
	private IntMxUserBasicInfoMapper intMxUserBasicInfoMapper;
	
	@Autowired
	private IntMxCallDetailsMapper intMxCallDetailsMapper;
	
	@Autowired
	private IntMxAlipayUserInfoMapper intMxAlipayUserInfoMapper;
	
	

	public String createBankTask(JSONObject json) {
		BankApi bankApi = this.getMoxieApiFactory().newApi(BankApi.class);
		// 创建任务
		TaskCreateReq req = TaskCreateReq.builder().add(ParamName.BANK, "ICBC")
				.add(ParamName.ACCOUNT, "62220212028680960").add(ParamName.PASSWORD, "123456")
				.add(ParamName.LOGIN_TYPE, "2").add(ParamName.LOGIN_TARGET, "4").add(ParamName.USER_ID, "12345680")
				.add(ParamName.ORIGIN, "2").build();

		String taskId = "";
		Response<TaskCreateRsp> taskCreateRspResponse = null;
		try {
			taskCreateRspResponse = bankApi.createTask(req).execute();
			if (taskCreateRspResponse.isSuccessful()) {
				taskId = taskCreateRspResponse.body().getTaskId();
				MarvelsLogUtil.getInstance().info("任务创建成功. taskId: " + taskId);
			} else {
				MarvelsLogUtil.getInstance().info("任务创建失败");
				System.out.println("status:" + taskCreateRspResponse.code());
				return null;
			}
		} catch (IOException e1) {
			MarvelsLogUtil.getInstance().error("createBankTask exception", e1);
		}

		boolean isTaskDone = false;
		// Step2 轮询状态
		long pollEndTime = System.currentTimeMillis() + 180 * 1000; // 轮询最多3分钟
		while (true) {
			Response<TaskStatusRsp> taskStatusRspResponse;
			try {
				taskStatusRspResponse = bankApi.getTaskStatus(taskId).execute();
				if (taskStatusRspResponse.isSuccessful()) {
					TaskStatusRsp taskStatusRsp = taskStatusRspResponse.body();
					String description = taskStatusRsp.getDescription();
					String phase = taskStatusRsp.getPhase();
					String phaseStatus = taskStatusRsp.getPhaseStatus();
					boolean finished = taskStatusRsp.isFinished();

					MarvelsLogUtil.getInstance().info(String.format("%s [%s] - %s", phase, phaseStatus, description));

					if (phaseStatus.equals("DOING")) {
						MarvelsLogUtil.getInstance().info("任务正在执行");
					}

					if (phaseStatus.equals("DONE_SUCC") && finished) {
						MarvelsLogUtil.getInstance().info("任务已完成");
						isTaskDone = true;
						break;
					}

					if (phaseStatus.equals("DONE_FAIL") || phaseStatus.equals("DONE_TIMEOUT")) {
						MarvelsLogUtil.getInstance().info("任务失败/超时");
						return null;
					}

					if (phaseStatus.equals("WAIT_CODE")) {
						String inputType = taskStatusRsp.getInput().getType();
						String result = null;
						if (taskStatusRsp.getInput().getType().equalsIgnoreCase("img")) {
							byte[] imageBytes = Base64.decodeBase64(taskStatusRsp.getInput().getValue());
							BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
							String[] options = { "OK" };
							JPanel panel = new JPanel();
							JLabel lbl = new JLabel("请输入验证码: ");
							JTextField txt = new JTextField(5);
							panel.add(lbl);
							panel.add(txt);
							int selectedOption = JOptionPane.showOptionDialog(null, panel, "验证码", JOptionPane.NO_OPTION,
									JOptionPane.QUESTION_MESSAGE, new ImageIcon(image), options, options[0]);
							if (selectedOption == 0) {
								result = txt.getText();
							}
						}
						if (result != null) {
							UserInput input = new UserInput(result);
							bankApi.input(taskId, input).execute();
						}
					}
				} else {
					int statusCode = taskCreateRspResponse.code();
					MarvelsLogUtil.getInstance().info("任务状态查询失败," + "status:" + statusCode + "\n" + taskCreateRspResponse.errorBody().string()
							+ "\n");
				}
			} catch (IOException e1) {
				MarvelsLogUtil.getInstance().error("createBankTask IOException", e1);
			}
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				MarvelsLogUtil.getInstance().error("createBankTask InterruptedException", e);
			}
			if (System.currentTimeMillis() > pollEndTime)
				break;
		}

		if (isTaskDone) {
			MarvelsLogUtil.getInstance().info("恭喜! 现在可以查数据了");
		}
		return taskId;
	}

	public String createCarrierTask(JSONObject json) {
		CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);

		TaskCreateReq req = TaskCreateReq.builder().add(ParamName.USER_ID, "1111").add(ParamName.ACCOUNT, "17707223031")
				.add(ParamName.PASSWORD, "sy6841856").add(ParamName.ORIGIN, "2").add(ParamName.REAL_NAME, "沈炎")
				.add(ParamName.ID_CARD, "420983199310107217").build();
		String taskId = "";
		Response<TaskCreateRsp> taskCreateRspResponse = null;
		try {
			taskCreateRspResponse = carrierApi.createTask(req).execute();
			if (taskCreateRspResponse.isSuccessful()) {
				TaskCreateRsp taskCreateRsp = taskCreateRspResponse.body();
				taskId = taskCreateRsp.getTaskId();
				System.out.println("任务创建成功. taskId: " + taskId);
			} else {
				System.out.println("任务创建失败");
				System.out.println("status:" + taskCreateRspResponse.code());
				System.out.println(taskCreateRspResponse.errorBody().string());
				return null;
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			MarvelsLogUtil.getInstance().error("createCarrierTask IOException", e1);

		}

		boolean isTaskDone = false;
		// Step2 轮询状态
		long pollEndTime = System.currentTimeMillis() + 180 * 1000; // 轮询最多3分钟
		while (true) {
			try {
				Response<TaskStatusRsp> taskStatusRspResponse = carrierApi.getTaskStatus(taskId).execute();
				if (taskStatusRspResponse.isSuccessful()) {
					TaskStatusRsp taskStatusRsp = taskStatusRspResponse.body();
					String description = taskStatusRsp.getDescription();
					String phase = taskStatusRsp.getPhase();
					String phaseStatus = taskStatusRsp.getPhaseStatus();
					boolean finished = taskStatusRsp.isFinished();

					System.out.println(String.format("%s [%s] - %s", phase, phaseStatus, description));

					if (phaseStatus.equals("DOING")) {
						System.out.println("任务正在执行");
					}

					if (phaseStatus.equals("DONE_SUCC") && finished) {
						System.out.println("任务已完成");
						isTaskDone = true;
						break;
					}

					if (phaseStatus.equals("DONE_FAIL") || phaseStatus.equals("DONE_TIMEOUT")) {
						System.out.println("任务失败/超时");
						return null;
					}

					if (phaseStatus.equals("WAIT_CODE")) {
						String inputType = taskStatusRsp.getInput().getType();
						System.out.println("等待用户输入,类型:" + inputType);
						if (taskStatusRsp.getInput().getType().equalsIgnoreCase("img")) {
							System.out.println("base64在线转图片,访问 http://codebeautify.org/base64-to-image-converter");
							System.out.println("请识别图片验证码:" + taskStatusRsp.getInput().getValue());
						}
						System.out.print("请输入验证码:");
						Scanner scanner = new Scanner(System.in);
						String result = scanner.nextLine();
						if (result != null) {
							UserInput input = new UserInput(result);
							carrierApi.input(taskId, input).execute();
						}
					}
				} else {
					System.out.println("任务状态查询失败");
					int statusCode = taskCreateRspResponse.code();
					System.out.println("status:" + statusCode + "\n");
					System.out.println(taskCreateRspResponse.errorBody().string() + "\n");
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				MarvelsLogUtil.getInstance().error("createCarrierTask IOException 2", e1);
			}

			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				MarvelsLogUtil.getInstance().error("createCarrierTask InterruptedException 3", e);
			}
			if (System.currentTimeMillis() > pollEndTime)
				break;
		}

		if (isTaskDone) {
			System.out.println("恭喜! 现在可以查数据了");
		}
		return taskId;
	}

	public MobileBasicV3 obtainUseMobileBasic(String taskId, String mobile) {

		CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
		Response<MobileBasicV3> mbileBasicV3Response;
		MobileBasicV3 mobileBasicV3 = null;
		try {
			mbileBasicV3Response = carrierApi.getMobileBasic(mobile, taskId).execute();
			mobileBasicV3 = mbileBasicV3Response.body();

		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("obtainUseMobileBasic IOException 1", e);
		}

		return mobileBasicV3;
	}

	public BillDetail obtainUserBills(String mobile, Map<String, String> map) {

		CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
		Response<BillDetail> billDetailResponse;
		BillDetail BillDetail = null;
		try {
			billDetailResponse = carrierApi.getBills(mobile, map).execute();
			BillDetail = billDetailResponse.body();

		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("obtainUserBills IOException 1", e);
		}

		return BillDetail;
	}

	public VoiceCallDetailList obtainUserVoiceCalls(String mobile, Map<String, String> map) {
		CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
		Response<VoiceCallDetailList> voiceCallDetailListResponse;
		VoiceCallDetailList voiceCallDetailList = null;
		try {
			voiceCallDetailListResponse = carrierApi.getVoiceCalls(mobile, map).execute();
			voiceCallDetailList = voiceCallDetailListResponse.body();

		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("obtainUserVoiceCalls IOException 1", e);
		}

		return voiceCallDetailList;
	}

	public ShortMessageDetailV2 obtainUserShortMessages(String mobile, Map<String, String> map) {
		CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
		Response<ShortMessageDetailV2> shortMessageDetailV2Response;
		ShortMessageDetailV2 shortMessageDetailV2 = null;
		try {
			shortMessageDetailV2Response = carrierApi.getShortMessages(mobile, map).execute();
			shortMessageDetailV2 = shortMessageDetailV2Response.body();

		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("obtainUserShortMessages IOException 1", e);
		}

		return shortMessageDetailV2;
	}

	public ApiResponse<AllDataDetails> obtainAllDataDetails(String mobile, String taskId, String serialNum,
			String loanId, String channel) {
		ApiResponse<AllDataDetails> apiResponse = new ApiResponse<AllDataDetails>();
		if (PropertiesUtils.isTurnOffForSwitch("switch.mx0002")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			apiResponse.setCode(RespStatus.DISABLE.getCode());
			apiResponse.setMsg(RespStatus.DISABLE.getMsg());
			return apiResponse;
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
		Response<AllDataDetails> allDataDetailsResponse = null;
		AllDataDetails allDataDetails = null;
		String method = ThirdMethodConstants.MX0002;
		ThirdDataDeal thirdInterfaceUtil = new ThirdDataDeal();
		Date sTime = new Date();
		try {
			allDataDetailsResponse = carrierApi.getAllDataDetails(mobile, taskId).execute();
			allDataDetails = allDataDetailsResponse.body();
			status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
			apiResponse.setCode(RespStatus.SUCCESS.getCode());
			apiResponse.setMsg("魔蝎查询运营商聚合接口查询数据成功");
			if (null != allDataDetails) {
				thirdCode = allDataDetails.getCode();
				MarvelsLogUtil.getInstance().info(">>>>>>>>>>魔蝎查询运营商聚合接口查询数据不为空,loanId:" + loanId);
				//先查询int_mx_data_query_log 是否有成功的数据如果有则不插入
				EdcDataQueryLog queryLog=new EdcDataQueryLog();
				queryLog.setTableName("int_mx_data_query_log");
				queryLog.setLoanId(loanId);
				queryLog.setInterfaceCode(ThirdMethodConstants.MX0002);
				List<EdcDataQueryLog> list=edcDataQueryLogMapper.selectByLoanId(queryLog);
				if(CollectionUtils.isEmpty(list)){//查询loanId MX0002接口调用成功条数 如果记录大于0则不插入
					try {
						dGMoXieService.obtainAllDataDetails(allDataDetails, serialNum, loanId);
					} catch (Exception e) {
						status = LocalStatus.IN_DATABASE_FAIL.getCode(); // 查询成功，但是落库失败
						MarvelsLogUtil.getInstance().error(">>>>>>>>魔蝎查询运营商聚合接口落库异常,loanId:" + loanId, e);
						apiResponse.setCode(RespStatus.DATABASE_ERROR.getCode());
						apiResponse.setMsg("数据存库失败");
					}
				}
			} else {
				status = LocalStatus.SUCCESS_WITHOUT_DATA.getCode(); // 查询成功但无数据
				MarvelsLogUtil.getInstance().info("查询数据为null");
				MarvelsLogUtil.getInstance().info("=============>>>>获取账号运营商全部数据的聚合接口,loanId:" + loanId + ",taskId:" + taskId + ",mobile"
						+ mobile);
				apiResponse.setCode(RespStatus.NODATA.getCode());
				apiResponse.setMsg("查询数据为null");
			}

		} catch (IOException e) {
			status = LocalStatus.REQUEST_FAIL.getCode(); // 请求异常了，将状态置为请求失败
			MarvelsLogUtil.getInstance().error("=============>>>>魔蝎查询运营商聚合接口请求", e);
			apiResponse.setCode(RespStatus.REQ_ERROR.getCode());
			apiResponse.setMsg("魔蝎查询运营商聚合接口请求异常");
		}
		Date eTime = new Date();
		String reqBody = "手机号码：" + mobile + "，任务Id:" + taskId;
		if (apiResponse.getCode() != RespStatus.SUCCESS.getCode()) {
			saveErrorLog(serialNum, Integer.toString(apiResponse.getCode()), apiResponse.getMsg(), reqBody,
					"", channel, method, sTime, eTime);
		}
		saveLog(serialNum, Integer.toString(apiResponse.getCode()), apiResponse.getMsg(), reqBody,
				allDataDetailsResponse.toString(), channel, method, sTime, eTime, "", "");

		String resultLog = "";
		if (apiResponse.getCode() == RespStatus.SUCCESS.getCode()
				|| apiResponse.getCode() == RespStatus.DATABASE_ERROR.getCode()) {
			resultLog = "1";
		} else if (apiResponse.getCode() == RespStatus.NODATA.getCode()) {
			resultLog = "0";
		} else {
			resultLog = "-1";
		}
		saveCallCountLog(loanId, ThirdMethodConstants.MX0002, resultLog, ThirdProductChannelConstant.MOXIE.getCode(),
				"魔蝎查询运营商聚合接口");
		// 记入统一日志表
		saveDataQueryLogNew(serialNum + "_" + ThirdMethodConstants.MX0002, loanId, mobile, sTime,
				ThirdMethodConstants.MX0002, thirdCode, status, "int_mx_data_query_log", null);
		return apiResponse;
	}

	public ApiResponse<NumberReport> obtainUserMobileReport(Map<String, String> map, String mobile, String serialNum,
			String loanId, String channel) {
		ApiResponse apiResponse = new ApiResponse();
		if (PropertiesUtils.isTurnOffForSwitch("switch.mx0001")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			apiResponse.setCode(RespStatus.DISABLE.getCode());
			apiResponse.setMsg(RespStatus.DISABLE.getMsg());
			return apiResponse;
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
		Response<NumberReport> numberReportResponse = null;
		Date sTime = new Date();
		NumberReport numberReport = null;

		String method = ThirdMethodConstants.MX0001;
		MarvelsLogUtil.getInstance().info("===================魔蝎运营商数据获取用户报告请求参数:" + JSONObject.fromObject(map) + ",mobile+" + mobile
				+ ",loanId:" + loanId);
		try {

			numberReportResponse = carrierApi.getNumberReport(mobile, map).execute();
			numberReport = numberReportResponse.body();
			
			status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
			apiResponse.setCode(RespStatus.SUCCESS.getCode());
			apiResponse.setMsg("魔蝎查询用户报告成功");
			MarvelsLogUtil.getInstance().info("===================魔蝎运营商数据获取用户报告请求返回,mobile+" + mobile + ",loanId:" + loanId);
			if (null != numberReport) {
				thirdCode = numberReport.getCode();
				MarvelsLogUtil.getInstance().info("返回数据不为空");
				String message = null;
				//获取用户报告message
				try {
					MarvelsLogUtil.getInstance().info("运营商认证开始获取用户报告message信息,loan[" + loanId + "]");
					Response<MXUserReportCall> userReportCallResponse = carrierApi.getUserReportInfo(map.get("task_id"), "report").execute();
					MarvelsLogUtil.getInstance().info("运营商认证开始获取用户报告message信息,loan[" + loanId + "],响应信息：" + com.alibaba.fastjson.JSONObject.toJSONString(userReportCallResponse));
					MXUserReportCall mxUserReportCall = userReportCallResponse.body();
					if(null != mxUserReportCall && mxUserReportCall.getResult()){
						message = mxUserReportCall.getMessage();
					}
					MarvelsLogUtil.getInstance().info("运营商认证开始获取用户报告message信息完成,loan[" + loanId + "]");
				} catch (Exception e) {
					MarvelsLogUtil.getInstance().error("运营商认证开始获取用户报告message信息异常,loan[" + loanId + "]", e);
				}
				
				//先查询int_mx_data_query_log 是否有成功的数据如果有则不插入
				EdcDataQueryLog queryLog=new EdcDataQueryLog();
				queryLog.setTableName("int_mx_data_query_log");
				queryLog.setLoanId(loanId);
				queryLog.setInterfaceCode(ThirdMethodConstants.MX0001);
				List<EdcDataQueryLog> list=edcDataQueryLogMapper.selectByLoanId(queryLog);
				if(CollectionUtils.isEmpty(list)){//查询loanId MX0001接口调用成功条数 如果记录大于0则不插入
					try {
						dGMoXieService.obtainUserMobileReport(numberReport, serialNum, loanId, message);
					} catch (Exception e) {
						status = LocalStatus.IN_DATABASE_FAIL.getCode(); // 查询成功，但是落库失败
						MarvelsLogUtil.getInstance().error(">>>>>>>>魔蝎查询用户报告异常:loanId:" + loanId, e);
						apiResponse.setCode(RespStatus.DATABASE_ERROR.getCode());
						apiResponse.setMsg("魔蝎查询用户报告数据存库失败");
					}
				}
			} else {
				status = LocalStatus.SUCCESS_WITHOUT_DATA.getCode(); // 查询成功但无数据
				MarvelsLogUtil.getInstance().info("返回数据为空");
				MarvelsLogUtil.getInstance().info("=============>>>>查询用户报告,loanId:" + loanId + ",taskId:" + map.get("task_id") + ",mobile"
						+ mobile);
				apiResponse.setCode(RespStatus.NODATA.getCode());
				apiResponse.setMsg("魔蝎查询用户报告为null");
			}

		} catch (IOException e) {
			status = LocalStatus.REQUEST_FAIL.getCode(); // 请求异常了，将状态置为请求失败
			apiResponse.setCode(RespStatus.REQ_ERROR.getCode());
			apiResponse.setMsg("魔蝎查询用户报告请求异常");
			MarvelsLogUtil.getInstance().error("魔蝎查询用户报告请求异常", e);
		}
		Date eTime = new Date();
		if (apiResponse.getCode() != RespStatus.SUCCESS.getCode()) {
			saveErrorLog(serialNum, Integer.toString(apiResponse.getCode()), apiResponse.getMsg(), map.toString(),
					"", channel, method, sTime, eTime);
		}
		saveLog(serialNum, Integer.toString(apiResponse.getCode()), apiResponse.getMsg(), map.toString(),
				numberReportResponse.toString(), channel, method, sTime, eTime, "", "");

		String resultLog = "";
		if (apiResponse.getCode() == RespStatus.SUCCESS.getCode()
				|| apiResponse.getCode() == RespStatus.DATABASE_ERROR.getCode()) {
			resultLog = "1";
		} else if (apiResponse.getCode() == RespStatus.NODATA.getCode()) {
			resultLog = "0";
		} else {
			resultLog = "-1";
		}
		saveCallCountLog(loanId, ThirdMethodConstants.MX0001, resultLog, ThirdProductChannelConstant.MOXIE.getCode(),
				"魔蝎运营商数据获取用户报告");
		// 记入统一日志表
		saveDataQueryLogNew(serialNum + "_" + ThirdMethodConstants.MX0001, loanId, mobile, sTime,
				ThirdMethodConstants.MX0001, thirdCode, status, "int_mx_data_query_log", null);
		return apiResponse;
	}

	@Override
	public ApiResponse<MXReport> obtainUserMobileReportV2(Map<String, String> map, String mobile, String serialNum,
			String loanId, String channel) {
		ApiResponse apiResponse = new ApiResponse();
		if (PropertiesUtils.isTurnOffForSwitch("switch.mx0003")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			apiResponse.setCode(RespStatus.DISABLE.getCode());
			apiResponse.setMsg(RespStatus.DISABLE.getMsg());
			return apiResponse;
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
		Response<MXReport> numberReportResponse = null;
		Date eTime = new Date();
		MXReport mXReport = null;
		String method = ThirdMethodConstants.MX0003;
		MarvelsLogUtil.getInstance().info("===================魔蝎运营商数据获取用户报告v2请求参数:" + JSONObject.fromObject(map) + ",mobile+" + mobile
				+ ",loanId:" + loanId);
		try {

			numberReportResponse = carrierApi.getNumberReportV2(mobile, map).execute();
			mXReport = numberReportResponse.body();
			MarvelsLogUtil.getInstance().info("===================魔蝎运营商数据获取用户报告v2请求返回,mobile" + mobile + ",loanId:" + loanId);

			status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
			apiResponse.setCode(RespStatus.SUCCESS.getCode());
			apiResponse.setMsg("魔蝎查询用户报告成功");

			if (null != mXReport) {
				MarvelsLogUtil.getInstance().info("返回数据不为空,loanId:" + loanId);
				try {
					//先查询int_mx_data_query_log 是否有成功的数据如果有则不插入
					EdcDataQueryLog queryLog=new EdcDataQueryLog();
					queryLog.setTableName("int_mx_data_query_log");
					queryLog.setLoanId(loanId);
					queryLog.setInterfaceCode(ThirdMethodConstants.MX0003);
					List<EdcDataQueryLog> list=edcDataQueryLogMapper.selectByLoanId(queryLog);
					if(CollectionUtils.isEmpty(list)){//查询loanId MX0003接口调用成功条数 如果记录大于0则不插入
						MarvelsLogUtil.getInstance().info("===================魔蝎运营商数据获取用户报告v2请求落库开始,mobile" + mobile + ",loanId:" + loanId);
						dGMoXieService.obtainAllDataDetailsv2(mXReport, serialNum, loanId);
						MarvelsLogUtil.getInstance().info("===================魔蝎运营商数据获取用户报告v2请求结束,mobile" + mobile + ",loanId:" + loanId);
					}
				} catch (Exception e) {
					status = LocalStatus.IN_DATABASE_FAIL.getCode(); // 查询成功，但是落库失败
					apiResponse.setCode(RespStatus.DATABASE_ERROR.getCode());
					apiResponse.setMsg("魔蝎查询用户报告v2数据存库失败");
					MarvelsLogUtil.getInstance().error(">>>>>>>>魔蝎查询用户报告v2数据存库失败:loanId:" + loanId, e);
				}
			} else {
				status = LocalStatus.SUCCESS_WITHOUT_DATA.getCode(); // 查询成功但无数据
				MarvelsLogUtil.getInstance().info("返回数据为空");
				MarvelsLogUtil.getInstance().info("=============>>>>查询用户报告,loanId:" + loanId + ",taskId:" + map.get("task_id") + ",mobile"
						+ mobile);
				apiResponse.setCode(RespStatus.NODATA.getCode());
				apiResponse.setMsg("魔蝎查询用户报告为null");
			}

		} catch (IOException e) {
			status = LocalStatus.REQUEST_FAIL.getCode(); // 请求异常了，将状态置为请求失败

			apiResponse.setCode(RespStatus.REQ_ERROR.getCode());
			apiResponse.setMsg("魔蝎查询用户报告请求异常");
			MarvelsLogUtil.getInstance().error("魔蝎查询用户报告v2请求异常,loanId" + loanId, e);

		}
		Date sTime = new Date();
		if (apiResponse.getCode() != RespStatus.SUCCESS.getCode()) {
			saveErrorLog(serialNum, Integer.toString(apiResponse.getCode()), apiResponse.getMsg(), map.toString(),
					"", channel, method, sTime, eTime);
		}
		saveLog(serialNum, Integer.toString(apiResponse.getCode()), apiResponse.getMsg(), map.toString(),
				numberReportResponse.toString(), channel, method, sTime, eTime, "", "");

		String resultLog = "";
		if (apiResponse.getCode() == RespStatus.SUCCESS.getCode()
				|| apiResponse.getCode() == RespStatus.DATABASE_ERROR.getCode()) {
			resultLog = "1";
		} else if (apiResponse.getCode() == RespStatus.NODATA.getCode()) {
			resultLog = "0";
		} else {
			resultLog = "-1";
		}
		saveCallCountLog(loanId, ThirdMethodConstants.MX0003, resultLog, ThirdProductChannelConstant.MOXIE.getCode(),
				"魔蝎运营商数据获取用户报告v2");
		// 记入统一日志表
		saveDataQueryLogNew(serialNum + "_" + ThirdMethodConstants.MX0003, loanId, mobile, sTime,
				ThirdMethodConstants.MX0003, thirdCode, status, "int_mx_data_query_log", null);
		return apiResponse;
	}

	public String createChsiTask(JSONObject json) {
		// Step1 创建任务
		ChsiApi chsiApi = this.getMoxieApiFactory().newApi(ChsiApi.class);
		TaskCreateReq req = TaskCreateReq.builder().add(ParamName.ACCOUNT, "18326118706")
				.add(ParamName.PASSWORD, "5711667").add(ParamName.USER_ID, "12345680").add(ParamName.ORIGIN, "2")
				.add(ParamName.IP, "192.168.0.1").build();

		String taskId = "";
		Response<TaskCreateRsp> taskCreateRspRes = null;
		try {
			taskCreateRspRes = chsiApi.createTask(req).execute();
			if (taskCreateRspRes.isSuccessful()) {
				taskId = taskCreateRspRes.body().getTaskId();
				MarvelsLogUtil.getInstance().info("任务创建成功. taskId: " + taskId);
			} else {
				MarvelsLogUtil.getInstance().info("任务创建失败. status:" + taskCreateRspRes.code() + "\n" + taskCreateRspRes.errorBody().string());
				return null;
			}
		} catch (IOException e1) {
			MarvelsLogUtil.getInstance().error("createChsiTask IOException 1", e1);
		}

		boolean isTaskDone = false;
		// Step2 轮询状态
		long pollEndTime = System.currentTimeMillis() + 180 * 1000; // 轮询最多3分钟
		while (true) {
			Response<TaskStatusRsp> taskStatusRspResponse;
			try {
				taskStatusRspResponse = chsiApi.getTaskStatus(taskId).execute();
				if (taskStatusRspResponse.isSuccessful()) {
					TaskStatusRsp taskStatusRsp = taskStatusRspResponse.body();
					String description = taskStatusRsp.getDescription();
					String phase = taskStatusRsp.getPhase();
					String phaseStatus = taskStatusRsp.getPhaseStatus();
					boolean finished = taskStatusRsp.isFinished();

					MarvelsLogUtil.getInstance().info(String.format("%s [%s] - %s", phase, phaseStatus, description));
					if (phaseStatus.equals("DONE_SUCC") && finished) {
						MarvelsLogUtil.getInstance().info("任务成功创建");
						isTaskDone = true;
						break;
					}

					if (phaseStatus.equals("DONE_FAIL") || phaseStatus.equals("DONE_TIMEOUT")) {
						MarvelsLogUtil.getInstance().info("任务失败/超时");
						return null;
					}

					if (phaseStatus.equals("WAIT_CODE")) {
						String inputType = taskStatusRsp.getInput().getType();
						String result = null;
						if (taskStatusRsp.getInput().getType().equalsIgnoreCase("img")) {
							// System.out.println("base64在线转图片,访问
							// http://codebeautify.org/base64-to-image-converter");
							// System.out.println(taskStatusRsp.getInput().getValue());
							byte[] imageBytes = Base64.decodeBase64(taskStatusRsp.getInput().getValue());
							BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));

							// 演示demo使用弹窗效果 使用请求请结合实际需求
							String[] options = { "OK" };
							JPanel panel = new JPanel();
							JLabel lbl = new JLabel("请输入验证码: ");
							JTextField txt = new JTextField(5);
							panel.add(lbl);
							panel.add(txt);
							int selectedOption = JOptionPane.showOptionDialog(null, panel, "验证码", JOptionPane.NO_OPTION,
									JOptionPane.QUESTION_MESSAGE, new ImageIcon(image), options, options[0]);
							if (selectedOption == 0) {
								result = txt.getText();
							}
						}
						if (result != null) {
							UserInput input = new UserInput(result);
							chsiApi.input(taskId, input).execute();
						}
					}
				} else {
					int statusCode = taskCreateRspRes.code();
					MarvelsLogUtil.getInstance().info(
							"任务状态查询失败," + "status:" + statusCode + "\n" + taskCreateRspRes.errorBody().string() + "\n");
				}
			} catch (IOException e1) {
				MarvelsLogUtil.getInstance().error("createChsiTask IOException 2", e1);
			}

			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				MarvelsLogUtil.getInstance().error("createChsiTask InterruptedException 3", e);
			}
			if (System.currentTimeMillis() > pollEndTime)
				break;
		}

		if (isTaskDone) {

			MarvelsLogUtil.getInstance().info("任务成功创建，请调用查询数据接口。");
		}
		return taskId;
	}

	public StudentInfoList obtainStudentInfo(String taskId) {
		Response<EducationInfoList> educationResponse;
		ChsiApi chsiApi = this.getMoxieApiFactory().newApi(ChsiApi.class);
		StudentInfoList studentInfoList = null;
		try {
			educationResponse = chsiApi.getEducationInfo(taskId).execute();
			EducationInfoList educationResult = educationResponse.body();
			System.out.println("查询学历信息结果:\n" + educationResult.toString() + "\n");

			// 学籍信息
			Response<StudentInfoList> studentInfoListResponse = chsiApi.getStudentInfo(taskId).execute();
			studentInfoList = studentInfoListResponse.body();
			System.out.println("查询学籍信息结果:\n" + studentInfoList.toString() + "\n");
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("obtainStudentInfo IOException 1", e);
		}
		return studentInfoList;
	}

	public MoxieResponse createFundTask(Map<String, String> map) {
		// Step1 创建任务
		FundApi fundApi = this.getMoxieApiFactory().newApi(FundApi.class);
		String mobile = map.get("mobile");
		String loanId = map.get("loanId");
		String account = map.get("account");
		String areaCode = map.get("areaCode");
		String idCard = map.get("idCard");
		String password = map.get("password");
		String realName = map.get("realName");
		// account 账户名
		// area_code 地区编号
		// id_card 身份证号
		// login_type 登录类型
		// password 密码
		// real_name 姓名
		// sub_area 子区域
		// mobile 手机号
		// origin 任务发起方式
		// user_id 用户id(客户第三方系统用户唯一标示)
		// corp_account 单位账号
		// corp_name 单位名称
		MoxieResponse moxieResponse = new MoxieResponse();
		TaskCreateReq req = TaskCreateReq.builder().add(ParamName.ACCOUNT, account).add(ParamName.AREA_CODE, areaCode)
				.add(ParamName.PASSWORD, password).add(ParamName.ID_CARD, idCard).add(ParamName.REAL_NAME, realName)
				.add(ParamName.MOBILE, mobile).add(ParamName.LOGIN_TYPE, "1").add(ParamName.LOGIN_TARGET, "4")
				.add(ParamName.USER_ID, loanId).add(ParamName.ORIGIN, "2").add(ParamName.IP, "").build();

		String taskId = "";
		Response<TaskCreateRsp> taskCreateRspResponse = null;
		try {
			taskCreateRspResponse = fundApi.createTask(req).execute();
			if (!taskCreateRspResponse.isSuccessful()) {
				MarvelsLogUtil.getInstance().info("任务创建失败," + "status:" + taskCreateRspResponse.code() + "/n"
						+ taskCreateRspResponse.errorBody().string() + ",mobile:" + mobile);
				moxieResponse.setCode(-1);
				moxieResponse.setMsg(taskCreateRspResponse.errorBody().string());
				// responseMap.put("groupId",
				// SystemUtil.objectToJsonStr(moxieResponse));
				// pushFaceSigService.pushFacePush(responseMap);
				return moxieResponse;
			}
		} catch (IOException e1) {
			MarvelsLogUtil.getInstance().error("createFundTask IOException 1", e1);
			moxieResponse.setCode(-2);
			moxieResponse.setMsg("魔蝎运营商任务创建异常");
			return moxieResponse;
		}
		taskId = taskCreateRspResponse.body().getTaskId();
		boolean isTaskDone = false;
		// Step2 轮询状态
		long pollEndTime = System.currentTimeMillis() + 180 * 1000; // 轮询最多3分钟
		while (true) {
			Response<TaskStatusRsp> taskStatusRspResponse;
			try {
				taskStatusRspResponse = fundApi.getTaskStatus(taskId).execute();
				if (!taskStatusRspResponse.isSuccessful()) {

					TaskStatusRsp taskStatusRsp = taskStatusRspResponse.body();
					String description = taskStatusRsp.getDescription();
					String phase = taskStatusRsp.getPhase();
					String phaseStatus = taskStatusRsp.getPhaseStatus();
					boolean finished = taskStatusRsp.isFinished();

					System.out.println(String.format("%s [%s] - %s", phase, phaseStatus, description));

					if (phaseStatus.equals("DONE_SUCC") && finished) {

						MarvelsLogUtil.getInstance().info("任务已完成");
						isTaskDone = true;

						Map<String, String> dataMap = new HashMap<String, String>();
						dataMap.put("taskId", taskId);
						dataMap.put("loanId", loanId);
						MoxieFundThread moxieFundThread = new MoxieFundThread();
						moxieFundThread.setMap(dataMap);
						Thread thread = new Thread(moxieFundThread);
						thread.start();

						moxieResponse.setCode(0);
						moxieResponse.setTaskId(taskId);
						moxieResponse.setMsg("魔蝎公积金任务创建成功");

						break;
					}

					if (phaseStatus.equals("DONE_FAIL") || phaseStatus.equals("DONE_TIMEOUT")) {
						MarvelsLogUtil.getInstance().info("任务失败/超时");
						moxieResponse.setCode(-1);
						moxieResponse.setMsg("魔蝎公积金任务创建超时");
						return moxieResponse;
					}

					if (phaseStatus.equals("WAIT_CODE")) {
						String inputType = taskStatusRsp.getInput().getType();
						String result = null;
						if (taskStatusRsp.getInput().getType().equalsIgnoreCase("img")) {
							// System.out.println("base64在线转图片,访问
							// http://codebeautify.org/base64-to-image-converter");
							// System.out.println(taskStatusRsp.getInput().getValue());
							byte[] imageBytes = Base64.decodeBase64(taskStatusRsp.getInput().getValue());
							BufferedImage image = null;
							try {
								image = ImageIO.read(new ByteArrayInputStream(imageBytes));
							} catch (IOException e) {
								e.printStackTrace();
								moxieResponse.setCode(-1);
								moxieResponse.setMsg("魔蝎公积金任务创建异常");
								return moxieResponse;
							}
							moxieResponse.setImg(true);
							moxieResponse.setCode(1);
							moxieResponse.setTaskId(taskId);
							moxieResponse.setBase64Img(taskStatusRsp.getInput().getValue());
							return moxieResponse;
						}
					}
				} else {

					int statusCode = taskCreateRspResponse.code();
					MarvelsLogUtil.getInstance().info("魔蝎公积金任务状态查询失败," + "status:" + statusCode + "\n" + ",mobile" + mobile);
					moxieResponse.setCode(-1);
					moxieResponse.setMsg(taskCreateRspResponse.errorBody().string());
					return moxieResponse;
				}
			} catch (IOException e1) {
				MarvelsLogUtil.getInstance().error("出现异常", e1);
				moxieResponse.setCode(-2);
				moxieResponse.setMsg("魔蝎运营商任务创建异常");
				return moxieResponse;
			}

			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
				moxieResponse.setCode(-2);
				moxieResponse.setMsg("魔蝎运营商任务创建异常");
				return moxieResponse;
			}
			if (System.currentTimeMillis() > pollEndTime)
				break;
		}

		return moxieResponse;
	}

	public ApiResponse<UserFundRecord> obtainUserFundRecord(String taskId, String serialNum, String loanId,
			String channel) {
		ApiResponse<UserFundRecord> apiResponse = new ApiResponse<UserFundRecord>();
		if (PropertiesUtils.isTurnOffForSwitch("switch.mx0005")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			apiResponse.setCode(RespStatus.DISABLE.getCode());
			apiResponse.setMsg(RespStatus.DISABLE.getMsg());
			return apiResponse;
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		FundApi fundApi = this.getMoxieApiFactory().newApi(FundApi.class);
		Response<UserFundRecord> fundResponse;
		UserFundRecord fundResult = null;
		String method = ThirdMethodConstants.MX0005;

		Date sTime = new Date();
		MarvelsLogUtil.getInstance().info("===================魔蝎查询公积金全部信息请求参数:" + "taskId+" + taskId + ",loanId:" + loanId);
		try {
			fundResponse = fundApi.getFund(taskId).execute();
			status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据

			MarvelsLogUtil.getInstance().info("===================魔蝎查询公积金全部信息返回:" + "taskId+" + taskId + ",loanId:" + loanId + ",参数:"
					+ JSONObject.fromObject(fundResponse));

			fundResult = fundResponse.body();
			if (fundResult != null) {
				try {
					dGMoXieService.obtainUserFundRecord(fundResult, serialNum, loanId);
				} catch (Exception e) {
					status = LocalStatus.IN_DATABASE_FAIL.getCode(); // 查询成功，但是落库失败
					e.printStackTrace();
					apiResponse.setCode(RespStatus.DATABASE_ERROR.getCode());
					apiResponse.setMsg("魔蝎查询公积金全部信息存库失败");
					MarvelsLogUtil.getInstance().error("魔蝎查询公积金全部信息存库失败,loanId" + loanId, e);
				}
			} else {
				status = LocalStatus.SUCCESS_WITHOUT_DATA.getCode(); // 查询成功但无数据
				apiResponse.setMsg("魔蝎查询公积金全部信息返回为空");
				apiResponse.setCode(RespStatus.NODATA.getCode());
				MarvelsLogUtil.getInstance().info("魔蝎查询公积金全部信息返回为空,loanId" + loanId);
			}
		} catch (IOException e) {
			status = LocalStatus.REQUEST_FAIL.getCode(); // 请求异常了，将状态置为请求失败
			apiResponse.setCode(RespStatus.REQ_ERROR.getCode());
			apiResponse.setMsg("魔蝎查询公积金全部信息异常");
			MarvelsLogUtil.getInstance().error("魔蝎查询公积金全部信息异常,loanId" + loanId, e);
		}
		Date eTime = new Date();
		if (apiResponse.getCode() != RespStatus.SUCCESS.getCode()) {
			saveErrorLog(serialNum, Integer.toString(apiResponse.getCode()), apiResponse.getMsg(), taskId,
					JSONObject.fromObject(fundResult).toString(), channel, method, sTime, eTime);
		}
		saveLog(serialNum, Integer.toString(apiResponse.getCode()), apiResponse.getMsg(), taskId,
				JSONObject.fromObject(fundResult).toString(), channel, method, sTime, eTime, "", "");

		String resultLog = "";
		if (apiResponse.getCode() == RespStatus.SUCCESS.getCode()
				|| apiResponse.getCode() == RespStatus.DATABASE_ERROR.getCode()) {
			resultLog = "1";
		} else if (apiResponse.getCode() == RespStatus.NODATA.getCode()) {
			resultLog = "0";
		} else {
			resultLog = "-1";
		}
		saveCallCountLog(loanId, ThirdMethodConstants.MX0005, resultLog, ThirdProductChannelConstant.MOXIE.getCode(),
				"魔蝎查询公积金全部信息");
		// 记入统一日志表
		saveDataQueryLogNew(serialNum, loanId, null, sTime, ThirdMethodConstants.MX0005, thirdCode, status,
				"int_mx_data_query_log", null);
		return apiResponse;
	}

	public UserInfo obtainUserFundBaseRecord(String taskId) {
		FundApi fundApi = this.getMoxieApiFactory().newApi(FundApi.class);
		UserInfo fundbase = null;
		Response<UserInfo> baseResponse;
		try {
			baseResponse = fundApi.getFundBase(taskId).execute();
			fundbase = baseResponse.body();
			System.out.println("查询基本信息:\n" + fundbase.toString() + "\n");
		} catch (IOException e) {
			e.printStackTrace();
		}

		return fundbase;
	}

	public List<BillRecord> obtainUserFundExitRecord(String taskId) {
		FundApi fundApi = this.getMoxieApiFactory().newApi(FundApi.class);
		Response<List<BillRecord>> billRecordResponse;
		List<BillRecord> billRecord = null;
		try {
			billRecordResponse = fundApi.getFundBill(taskId).execute();
			billRecord = billRecordResponse.body();
			System.out.println("查询缴存信息:\n" + billRecord.toString() + "\n");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return billRecord;
	}

	public List<LoanInfo> obtainUserFundBorrowRecord(String taskId) {
		FundApi fundApi = this.getMoxieApiFactory().newApi(FundApi.class);
		Response<List<LoanInfo>> loanInfoResponse;
		List<LoanInfo> loanInfo = null;
		try {
			loanInfoResponse = fundApi.getFundLoan(taskId).execute();
			loanInfo = loanInfoResponse.body();
			System.out.println("查询贷款信息:\n" + loanInfo.toString() + "\n");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return loanInfo;
	}

	public List<LoanRepayRecord> obtainUserFundRepayRecord(String taskId) {
		FundApi fundApi = this.getMoxieApiFactory().newApi(FundApi.class);
		Response<List<LoanRepayRecord>> loanRepayRecordResponse;
		List<LoanRepayRecord> loanRepayRecord = null;
		try {
			loanRepayRecordResponse = fundApi.getFundLoanRepayRecord(taskId).execute();
			loanRepayRecord = loanRepayRecordResponse.body();
			System.out.println("查询还款信息:\n" + loanRepayRecord.toString() + "\n");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return loanRepayRecord;
	}

	public String createMailTask(JSONObject json) {
		MailApi mailApi = this.getMoxieApiFactory().newApi(MailApi.class);
		// Step1 创建任务
		TaskCreateReq req = TaskCreateReq.builder().add(ParamName.ACCOUNT, "26332502@qq.com")
				.add(ParamName.PASSWORD, "87529996").add(ParamName.USER_ID, "12345680").add(ParamName.ORIGIN, "2")
				.add(ParamName.IP, "120.26.215.133").build();

		String taskId = null;
		Response<TaskCreateRsp> taskCreateRspResponse = null;
		try {
			taskCreateRspResponse = mailApi.createTask(req).execute();
			if (taskCreateRspResponse.isSuccessful()) {
				TaskCreateRsp taskCreateRsp = taskCreateRspResponse.body();
				taskId = taskCreateRsp.getTaskId();
				System.out.println("任务创建成功. taskId: " + taskId);
			} else {
				System.out.println("任务创建失败");
				System.out.println("status:" + taskCreateRspResponse.code());
				System.out.println(taskCreateRspResponse.errorBody().string());
				return null;
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			MarvelsLogUtil.getInstance().error("出现异常", e1);
		}

		boolean isTaskDone = false;
		// Step2 轮询状态
		long pollEndTime = System.currentTimeMillis() + 180 * 1000; // 轮询最多3分钟
		while (true) {
			Response<TaskStatusRsp> taskStatusRspResponse;
			try {
				taskStatusRspResponse = mailApi.getTaskStatus(taskId).execute();
				if (taskStatusRspResponse.isSuccessful()) {
					TaskStatusRsp taskStatusRsp = taskStatusRspResponse.body();
					String description = taskStatusRsp.getDescription();
					String phase = taskStatusRsp.getPhase();
					String phaseStatus = taskStatusRsp.getPhaseStatus();
					boolean finished = taskStatusRsp.isFinished();

					System.out.println(String.format("%s [%s] - %s", phase, phaseStatus, description));

					if (phaseStatus.equals("DOING")) {
						System.out.println("任务正在执行");
					}

					if (phaseStatus.equals("DONE_SUCC") && finished) {
						System.out.println("任务已完成");
						isTaskDone = true;
						break;
					}

					if (phaseStatus.equals("DONE_FAIL") || phaseStatus.equals("DONE_TIMEOUT")) {
						System.out.println("任务失败/超时");
						return null;
					}

					if (phaseStatus.equals("WAIT_CODE")) {
						String inputType = taskStatusRsp.getInput().getType();
						System.out.println("等待用户输入,类型:" + inputType);
						String result = null;
						if (taskStatusRsp.getInput().getType().equalsIgnoreCase("img")) {
							System.out.println("base64在线转图片,访问 http://codebeautify.org/base64-to-image-converter");
							System.out.println("图片验证码(base64): " + taskStatusRsp.getInput().getValue());
							byte[] imageBytes = Base64.decodeBase64(taskStatusRsp.getInput().getValue());
							BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
							// 演示demo使用弹窗效果 使用请求请结合实际需求
							String[] options = { "OK" };
							JPanel panel = new JPanel();
							JLabel lbl = new JLabel("请输入验证码: ");
							JTextField txt = new JTextField(5);
							panel.add(lbl);
							panel.add(txt);
							int selectedOption = JOptionPane.showOptionDialog(null, panel, "验证码", JOptionPane.NO_OPTION,
									JOptionPane.QUESTION_MESSAGE, new ImageIcon(image), options, options[0]);
							if (selectedOption == 0) {
								result = txt.getText();
							}
						} else if (taskStatusRsp.getInput().getType().equalsIgnoreCase("idpPass")) {
							System.out.println("等待用户输入独立密码");
							// 演示demo使用弹窗效果 使用请求请结合实际需求
							String[] options = { "OK" };
							JPanel panel = new JPanel();
							JLabel lbl = new JLabel("请输入独立密码: ");
							JTextField txt = new JTextField(5);
							panel.add(lbl);
							panel.add(txt);
							int selectedOption = JOptionPane.showOptionDialog(null, panel, "独立密码",
									JOptionPane.NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
							if (selectedOption == 0) {
								result = txt.getText();
							}
						}

						if (result != null) {
							UserInput input = new UserInput(result);
							mailApi.input(taskId, input).execute();
						}
					}
				} else {
					System.out.println("任务状态查询失败");
					int statusCode = taskCreateRspResponse.code();
					System.out.println("status:" + statusCode + "\n");
					System.out.println(taskCreateRspResponse.errorBody().string() + "\n");
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				MarvelsLogUtil.getInstance().error("出现异常", e1);
			}

			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (System.currentTimeMillis() > pollEndTime)
				break;
		}

		if (isTaskDone) {
			System.out.println("恭喜! 现在可以查数据了");
		}
		return taskId;
	}

	public EmailBillList obtainCreditBillRecord(String taskId) {
		MailApi mailApi = this.getMoxieApiFactory().newApi(MailApi.class);
		Response<EmailBillList> billResponse;
		EmailBillList billResult = null;
		try {
			billResponse = mailApi.getBillsByTaskId(taskId).execute();
			billResult = billResponse.body();
			MarvelsLogUtil.getInstance().info("查询信用卡账单结果:\n" + ObjectMappers.getObjectMapper().writeValueAsString(billResult) + "\n");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return billResult;
	}

	public EmailBillShoppingSheetList obtainCreditConsumBillRecord(String taskId) {
		MailApi mailApi = this.getMoxieApiFactory().newApi(MailApi.class);
		Response<EmailBillList> billResponse;
		EmailBillShoppingSheetList emailBillShoppingSheetList = null;
		EmailBillList billResult = null;
		try {
			billResponse = mailApi.getBillsByTaskId(taskId).execute();
			billResult = billResponse.body();
			if (billResult.getSize() > 0) {
				Call<EmailBillShoppingSheetList> shoppingSheetList = mailApi
						.getBillShoppingSheets(billResult.getBills().get(0).getBillId(), 1, 10);
				Response<EmailBillShoppingSheetList> shoppingSheetListResponse = shoppingSheetList.execute();
				emailBillShoppingSheetList = shoppingSheetListResponse.body();
				MarvelsLogUtil.getInstance().info("查询信用卡账单消费记录结果:\n"
						+ ObjectMappers.getObjectMapper().writeValueAsString(emailBillShoppingSheetList) + "\n");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return emailBillShoppingSheetList;
	}

	public EmailBillInstallmentList obtainCreditConsumPeriodBillRecord(String taskId) {
		MailApi mailApi = this.getMoxieApiFactory().newApi(MailApi.class);
		Response<EmailBillList> billResponse;
		EmailBillInstallmentList emailBillInstallmentList = null;

		EmailBillList billResult = null;
		try {
			billResponse = mailApi.getBillsByTaskId(taskId).execute();
			billResult = billResponse.body();
			if (billResult.getSize() > 0) {
				Call<EmailBillInstallmentList> installments = mailApi
						.getBillInstallments(billResult.getBills().get(0).getBillId(), 1, 10);
				Response<EmailBillInstallmentList> installmentsResponse = installments.execute();
				emailBillInstallmentList = installmentsResponse.body();
				MarvelsLogUtil.getInstance().info("查询信用卡账单分期结果:\n"
						+ ObjectMappers.getObjectMapper().writeValueAsString(emailBillInstallmentList) + "\n");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return emailBillInstallmentList;
	}

	public String createInsurancePolicyTask(JSONObject json) {
		// Step1 创建任务
		InsurancePolicyApi insurancePolicy = this.getMoxieApiFactory().newApi(InsurancePolicyApi.class);
		JSONObject argumentsJson = new JSONObject();
		argumentsJson.put(ParamName.Username, "2432342342334324");
		argumentsJson.put(ParamName.Password, "232321198409200913");
		argumentsJson.put(ParamName.Idp_Pass, "");
		argumentsJson.put(ParamName.Login_Type, "policynum");
		argumentsJson.put(ParamName.Login_Target, "-1");
		argumentsJson.put(ParamName.Cookie, "");
		JSONObject contextJson = new JSONObject();
		contextJson.put(ParamName.Ip, "");
		contextJson.put(ParamName.City, "");
		contextJson.put(ParamName.Province, "");
		contextJson.put(ParamName.Lat, "");
		contextJson.put(ParamName.Lon, "");
		contextJson.put(ParamName.Name, "");
		contextJson.put(ParamName.Phone, "");
		contextJson.put(ParamName.Idcard, "");
		JSONObject paramJson = new JSONObject();
		paramJson.put(ParamName.Origin, "2");
		paramJson.put(ParamName.Phase, "NEW");
		JSONObject headerJSON = new JSONObject();
		paramJson.put(ParamName.Headers, headerJSON.toString());
		paramJson.put(ParamName.Arguments, argumentsJson.toString());

		JSONObject jsonObject = new JSONObject();
		jsonObject.put(ParamName.USER_ID, "0253349");
		jsonObject.put(ParamName.Type, "INSURANCE");
		jsonObject.put(ParamName.Sub_Type, "PAIC");
		jsonObject.put(ParamName.Param, paramJson.toString());
		jsonObject.put(ParamName.Context, contextJson.toString());
		// TaskCreateReq req = TaskCreateReq.builder().add(ParamName.USER_ID,
		// "0253349").add(ParamName.Type, "INSURANCE")
		// .add(ParamName.Sub_Type, "PICC").add(ParamName.Param,
		// paramJson.toString())
		// .add(ParamName.Context, contextJson.toString()).build();

		String taskId = "";
		Response<TaskCreateRsp> taskCreateRspResponse = null;
		try {
			taskCreateRspResponse = insurancePolicy.createTask(jsonObject).execute();
			if (taskCreateRspResponse.isSuccessful()) {
				TaskCreateRsp taskCreateRsp = taskCreateRspResponse.body();
				taskId = taskCreateRsp.getTaskId();
				System.out.println("任务创建成功. taskId: " + taskId);
			} else {
				System.out.println("任务创建失败");
				System.out.println("status:" + taskCreateRspResponse.code());
				System.out.println(taskCreateRspResponse.errorBody().string());
				return null;
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			MarvelsLogUtil.getInstance().error("出现异常", e1);
		}

		boolean isTaskDone = false;
		// Step2 轮询状态
		long pollEndTime = System.currentTimeMillis() + 180 * 1000; // 轮询最多3分钟
		while (true) {
			Response<TaskStatusRsp> taskStatusRspResponse;
			try {
				taskStatusRspResponse = insurancePolicy.getTaskStatus(taskId).execute();
				if (taskStatusRspResponse.isSuccessful()) {
					TaskStatusRsp taskStatusRsp = taskStatusRspResponse.body();
					String description = taskStatusRsp.getDescription();
					String phase = taskStatusRsp.getPhase();
					String phaseStatus = taskStatusRsp.getPhaseStatus();
					boolean finished = taskStatusRsp.isFinished();

					System.out.println(String.format("%s [%s] - %s", phase, phaseStatus, description));

					if (phaseStatus.equals("DONE_SUCC") && finished) {
						System.out.println("任务已完成");
						isTaskDone = true;
						break;
					}

					if (phaseStatus.equals("DONE_FAIL") || phaseStatus.equals("DONE_TIMEOUT")) {
						System.out.println("任务失败/超时");
						return null;
					}

					if (phaseStatus.equals("WAIT_CODE")) {
						String inputType = taskStatusRsp.getInput().getType();
						System.out.println("等待用户输入,类型:" + inputType);
						String result = null;
						if (taskStatusRsp.getInput().getType().equalsIgnoreCase("img")) {
							System.out.println("base64在线转图片,访问 http://codebeautify.org/base64-to-image-converter");
							System.out.println(taskStatusRsp.getInput().getValue());
							byte[] imageBytes = Base64.decodeBase64(taskStatusRsp.getInput().getValue());
							BufferedImage image = null;
							try {
								image = ImageIO.read(new ByteArrayInputStream(imageBytes));
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

							// 演示demo使用弹窗效果 使用请求请结合实际需求
							String[] options = { "OK" };
							JPanel panel = new JPanel();
							JLabel lbl = new JLabel("请输入验证码: ");
							JTextField txt = new JTextField(5);
							panel.add(lbl);
							panel.add(txt);
							int selectedOption = JOptionPane.showOptionDialog(null, panel, "验证码", JOptionPane.NO_OPTION,
									JOptionPane.QUESTION_MESSAGE, new ImageIcon(image), options, options[0]);
							if (selectedOption == 0) {
								result = txt.getText();
							}
						}
						if (result != null) {
							UserInput input = new UserInput(result);
							try {
								insurancePolicy.input(taskId, input).execute();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				} else {
					System.out.println("任务状态查询失败");
					int statusCode = taskCreateRspResponse.code();
					System.out.println("status:" + statusCode + "\n");
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				MarvelsLogUtil.getInstance().error("出现异常", e1);
			}

			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (System.currentTimeMillis() > pollEndTime)
				break;
		}

		if (isTaskDone) {
			System.out.println("恭喜! 现在可以查数据了");
		}

		return taskId;
	}

	public InsurancePolicy obtainPolicyData(String taskId) {

		InsurancePolicyApi insurancePolicyApi = this.getMoxieApiFactory().newApi(InsurancePolicyApi.class);
		Response<InsurancePolicy> insurancePolicyResponse;
		InsurancePolicy insurancePolicy = null;
		try {
			insurancePolicyResponse = insurancePolicyApi.getPolicy(taskId).execute();
			insurancePolicy = insurancePolicyResponse.body();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return insurancePolicy;
	}

	@Override
	public String verifySMSCode(String taskId, String code) {

		CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
		UserInput input = new UserInput(code);
		try {
			carrierApi.input(taskId, input).execute();
		} catch (IOException e) {

			e.printStackTrace();
		}
		return taskId;
	}

	@Override
	public String getCityData() {

		FundApi fundApi = this.getMoxieApiFactory().newApi(FundApi.class);
		Response<Object> getCityRspResponse = null;
		String object = "";
		try {
			getCityRspResponse = fundApi.getCityData().execute();

			if (getCityRspResponse.isSuccessful()) {
				object = getCityRspResponse.body().toString();
				System.out.println("任务创建成功. taskId: " + object);
			} else {
				System.out.println("任务创建失败. status:" + getCityRspResponse.code());
				System.out.println(getCityRspResponse.errorBody().string());

			}
		} catch (IOException e) {

			e.printStackTrace();
		}

		return object;
	}

	@Override
	public MoxieResponse createCarrierTaskV2(Map<String, String> map) {
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		String loanId = map.get("loanId");// 进件单号
		String orderNumber = map.get("orderNumber");// 订单号
		MoxieResponse moxieResponse = new MoxieResponse();
		MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "创建任务开始时间" + DateUtil.dataFormat());
		TaskCreateReq req = TaskCreateReq.builder().add(ParamName.USER_ID, map.get("user_id"))
				.add(ParamName.ACCOUNT, map.get("mobile")).add(ParamName.PASSWORD, map.get("password"))
				.add(ParamName.ORIGIN, "2").add(ParamName.REAL_NAME, map.get("realName"))
				.add(ParamName.ID_CARD, map.get("idNumber")).build();
		String taskId = "";
		Response<TaskCreateRsp> taskCreateRspResponse = null;
		try {
			CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
			MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "创建任务请求时间" + DateUtil.dataFormat());
			taskCreateRspResponse = carrierApi.createTask(req).execute();
			MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "创建任务响应时间" + DateUtil.dataFormat());
			if (!taskCreateRspResponse.isSuccessful()) {
				MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "手机号码:" + map.get("mobile") + "任务创建失败" + ",status:"
						+ taskCreateRspResponse.code() + ",信息:" + taskCreateRspResponse.errorBody().string());
				moxieResponse.setCode(-1);
				moxieResponse.setMsg(taskCreateRspResponse.errorBody().string());
				return moxieResponse;
			}
			boolean isTaskDone = false;
			// Step2 轮询状态
			long pollEndTime = System.currentTimeMillis() + thirdProperties.getPolling_time(); // 轮询最多3分钟
			taskId = taskCreateRspResponse.body().getTaskId();
			while (true) {
				MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "查询状态时间" + DateUtil.dataFormat());
				Response<TaskStatusRsp> taskStatusRspResponse = carrierApi.getTaskStatus(taskId).execute();
				MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "查询状态响应时间" + DateUtil.dataFormat());
				if (taskStatusRspResponse.isSuccessful()) {
					TaskStatusRsp taskStatusRsp = taskStatusRspResponse.body();
					String description = taskStatusRsp.getDescription();
					String phase = taskStatusRsp.getPhase();
					String phaseStatus = taskStatusRsp.getPhaseStatus();
					boolean finished = taskStatusRsp.isFinished();
					MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "手机号:" + map.get("mobile") + ",状态码:" + phaseStatus
							+ ",描述:" + description);
					if (phaseStatus.equals("WAIT_CODE")) {
						String inputType = taskStatusRsp.getInput().getType();
						System.out.println("等待用户输入,类型:" + inputType);
						if (taskStatusRsp.getInput().getType().equalsIgnoreCase("img")) {// 图片
							MarvelsLogUtil.getInstance().info("===============loanId" + loanId
									+ "在线转图片,访问 http://codebeautify.org/base64-to-image-converter");
							MarvelsLogUtil.getInstance().info("==========>>>手机号码:" + map.get("mobile") + "识别图片验证码:"
									+ taskStatusRsp.getInput().getValue());
							isTaskDone = true;
							moxieResponse.setImg(true);
							moxieResponse.setCode(1);
							moxieResponse.setTaskId(taskId);
							moxieResponse.setBase64Img(taskStatusRsp.getInput().getValue());
							break;
						} else {// 短信
							isTaskDone = true;
							moxieResponse.setSmsCode(true);
							moxieResponse.setCode(1);
							moxieResponse.setTaskId(taskId);
							MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "手机号码:" + map.get("mobile") + "输入类型为验证码:");
							break;
						}
					}

					if (phaseStatus.equals("DONE_FAIL") || phaseStatus.equals("DONE_TIMEOUT")) {
						moxieResponse.setCode(-1);
						moxieResponse.setMsg(description);
						MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "手机号码:" + map.get("mobile") + "输入类型为验证码:");
						break;
					}
					if ((taskStatusRsp.isCanLeave() && !phaseStatus.equals("DONE_FAIL")
							&& !phaseStatus.equals("DONE_TIMEOUT")) || (phaseStatus.equals("DONE_SUCC") && finished)) {
						MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "创建任务已完成,持久化任务Id开始");
						isTaskDone = true;
						// 查询数据及落地
						Map<String, String> dataMap = new HashMap<String, String>();
						dataMap.put("task_id", taskId);
						dataMap.put("loanId", loanId);
						dataMap.put("orderNumber", orderNumber);
						dataMap.put("mobile", map.get("mobile"));
						MoXieCarrierThread moXieCarrierThread = new MoXieCarrierThread();
						moXieCarrierThread.setMap(dataMap);
						Thread thread = new Thread(moXieCarrierThread);
						thread.start();
						moxieResponse.setCode(0);
						moxieResponse.setTaskId(taskId);
						moxieResponse.setMsg("魔蝎运营商任务创建成功");
						MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "持久化任务Id同时break" + DateUtil.dataFormat());
						break;
					}

				} else {
					System.out.println("任务状态查询失败");
					int statusCode = taskCreateRspResponse.code();
					System.out.println("status:" + statusCode + "\n");
					System.out.println(taskCreateRspResponse.errorBody().string() + "\n");
					moxieResponse.setCode(-1);
					moxieResponse.setMsg(taskCreateRspResponse.errorBody().string());
					return moxieResponse;
				}
				Thread.sleep(2000);
				MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "创建任务休眠后继续轮询" + DateUtil.dataFormat());
				if (System.currentTimeMillis() > pollEndTime) {
					moxieResponse.setCode(-1);
					moxieResponse.setMsg("魔蝎运营商任务创建超时");
					break;
				}
			}

		} catch (Exception e1) {
			MarvelsLogUtil.getInstance().error("==========>>>魔蝎创建运营商任务时:", e1);
			moxieResponse.setCode(-2);
			moxieResponse.setMsg("魔蝎运营商任务创建异常");
			return moxieResponse;
		}
		MarvelsLogUtil.getInstance().info("===============>>>>查询运营商结束时间" + DateUtil.dataFormat());
		return moxieResponse;
	}

	@Override
	public MoxieResponse verifySMSCodeV2(Map<String, String> map) {
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		String loanId = map.get("loanId");// 进件单号
		String orderNumber = map.get("orderNumber");// 订单号
		String name = map.get("name");
		String idcard = map.get("idcard");
		MoxieResponse moxieResponse = new MoxieResponse();
		NumberReport numberReport = new NumberReport();
		String taskId = map.get("taskId");
		String code = map.get("code");
		String accumulationFund = map.get("accumulationFund");
		MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "验证短信验证码开始时间" + DateUtil.dataFormat());
		Map<String, String> responseMap = new HashMap<String, String>();
		// responseMap.put("userId", cid);
		CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
		UserInput input = new UserInput(code);
		try {
			MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "验证短信验证码请求时间" + DateUtil.dataFormat());
			Response<TaskVoidRsp> taskVoidRsp = carrierApi.input(taskId, input).execute();
			MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "验证短信验证码结束时间" + DateUtil.dataFormat());
			if (!taskVoidRsp.isSuccessful()) {
				MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "校验验证码" + taskVoidRsp.errorBody().string());
				moxieResponse.setCode(-1);
				moxieResponse.setMsg(taskVoidRsp.errorBody().string());
				return moxieResponse;
			}
			boolean isTaskDone = false;
			// Step2 轮询状态
			long pollEndTime = System.currentTimeMillis() + thirdProperties.getPolling_time(); // 轮询最多3分钟
			while (true) {
				MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "任务状态查询开始时间" + DateUtil.dataFormat());
				Response<TaskStatusRsp> taskStatusRspResponse = carrierApi.getTaskStatus(taskId).execute();
				MarvelsLogUtil.getInstance().info("===============loanId" + loanId + "任务状态查询结束时间" + DateUtil.dataFormat());
				if (taskStatusRspResponse.isSuccessful()) {
					TaskStatusRsp taskStatusRsp = taskStatusRspResponse.body();
					String description = taskStatusRsp.getDescription();
					String phase = taskStatusRsp.getPhase();
					String phaseStatus = taskStatusRsp.getPhaseStatus();
					boolean finished = taskStatusRsp.isFinished();
					System.out.println(String.format("%s [%s] - %s", phase, phaseStatus, description));

					if (phaseStatus.equals("WAIT_CODE")) {
						String inputType = taskStatusRsp.getInput().getType();
						MarvelsLogUtil.getInstance().info("===============loanId" + loanId + ",等待用户输入,类型:" + inputType);
						if (taskStatusRsp.getInput().getType().equalsIgnoreCase("img")) {// 图片
							MarvelsLogUtil.getInstance().info("===============loanId" + loanId
									+ "base64在线转图片,访问 http://codebeautify.org/base64-to-image-converter");
							MarvelsLogUtil.getInstance().info("=========>>>>请识别图片验证码:" + taskStatusRsp.getInput().getValue());
							isTaskDone = true;
							moxieResponse.setImg(true);
							moxieResponse.setCode(1);
							moxieResponse.setBase64Img(taskStatusRsp.getInput().getValue());
							break;
						} else {// 短信
							isTaskDone = true;
							moxieResponse.setSmsCode(true);
							moxieResponse.setCode(1);
							break;
						}
					}
					if (phaseStatus.equals("DONE_FAIL") || phaseStatus.equals("DONE_TIMEOUT")) {
						moxieResponse.setCode(-1);
						moxieResponse.setMsg(description);
						MarvelsLogUtil.getInstance().info("==========>>>进件单号:" + loanId + "任务失败/超时");
						break;
					}
					if ((taskStatusRsp.isCanLeave() && !phaseStatus.equals("DONE_FAIL")
							&& !phaseStatus.equals("DONE_TIMEOUT")) || (phaseStatus.equals("DONE_SUCC") && finished)) {
						MarvelsLogUtil.getInstance().info("==========>>>进件单号:" + loanId + "任务已完成");
						isTaskDone = true;
						// 查询数据及落地
						if (StringUtils.isNotEmpty(accumulationFund)) {
							Map<String, String> dataMap = new HashMap<String, String>();
							dataMap.put("taskId", taskId);
							dataMap.put("loanId", loanId);
							MoxieFundThread moxieFundThread = new MoxieFundThread();
							moxieFundThread.setMap(dataMap);
							Thread thread = new Thread(moxieFundThread);
							thread.start();

							moxieResponse.setCode(0);
							moxieResponse.setMsg("魔蝎公积金任务创建成功");
							break;
						} else {
							MarvelsLogUtil.getInstance().info("==========>>>进件单号:" + loanId + "持久化任务id开始" + DateUtil.dataFormat());
							Map<String, String> dataMap = new HashMap<String, String>();
							dataMap.put("task_id", taskId);
							dataMap.put("loanId", loanId);
							dataMap.put("orderNumber", orderNumber);
							dataMap.put("mobile", map.get("mobile"));
							MoXieCarrierThread moXieCarrierThread = new MoXieCarrierThread();
							moXieCarrierThread.setMap(dataMap);
							Thread thread = new Thread(moXieCarrierThread);
							thread.start();
							moxieResponse.setCode(0);
							moxieResponse.setMsg("魔蝎运营商任务创建成功");
							MarvelsLogUtil.getInstance().info("==========>>>进件单号:" + loanId + "异步持久化任务id同时break" + DateUtil.dataFormat());
							break;
						}

					}

				} else {
					MarvelsLogUtil.getInstance().info(taskStatusRspResponse.errorBody().string());
					int statusCode = taskStatusRspResponse.code();
					MarvelsLogUtil.getInstance().info("status:" + statusCode + "\n");
					MarvelsLogUtil.getInstance().info("==========>>>进件单号:" + loanId + ",错误信息" + taskStatusRspResponse.errorBody().string()
							+ "\n");
					moxieResponse.setCode(-1);
					moxieResponse.setMsg(taskStatusRspResponse.errorBody().string());
					return moxieResponse;
				}

				Thread.sleep(2000);
				MarvelsLogUtil.getInstance().info("==========>>>进件单号:" + loanId + "验证短信验证码轮询状态继续" + DateUtil.dataFormat());
				if (System.currentTimeMillis() > pollEndTime) {
					moxieResponse.setCode(-1);
					moxieResponse.setMsg("魔蝎运营商任务创建超时");
					break;
				}
			}

		} catch (Exception e1) {
			MarvelsLogUtil.getInstance().error("==========>>>进件单号:" + loanId + ",错误信息", e1);
			moxieResponse.setCode(-2);
			moxieResponse.setMsg("魔蝎运营商任务创建异常");
			return moxieResponse;
		}
		MarvelsLogUtil.getInstance().info("==========>>>进件单号:" + loanId + "验证短信验证码结束 时间" + DateUtil.dataFormat());
		return moxieResponse;
	}

	@Override
	public ApiResponse<RealNameAuthentication> realNameAuthentication(Map<String, String> map) {
		ApiResponse apiResponse = new ApiResponse();
		if (PropertiesUtils.isTurnOffForSwitch("switch.mx0006")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			apiResponse.setCode(RespStatus.DISABLE.getCode());
			apiResponse.setMsg(RespStatus.DISABLE.getMsg());
			return apiResponse;
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		String mobile = map.get("mobile");
		String loanId = map.get("loanId");
		map.put("element", "3");
		Date sTime = new Date();
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		String url = thirdProperties.getMx_baseUrl_new();
		MoxieApiFactory apiFactory = MoxieApiFactory.builder().withAuthToken(new AuthToken(ThirdPropertiesInitUtil.getThirdProperties().getMx_api_key(), ThirdPropertiesInitUtil.getThirdProperties().getMx_token()))
				.withBaseUrl(url).build();
		CarrierApi carrierApi = apiFactory.newApi(CarrierApi.class);
		Response<RealNameAuthentication> realNameAuthenticationResponse = null;
		Date eTime = new Date();
		RealNameAuthentication realNameAuthentication = null;
		String tradeNo = "";
		MarvelsLogUtil.getInstance().info("===================魔蝎用户手机号是否实名认证请求参数:" + JSONObject.fromObject(map) + ",mobile+" + mobile
				+ ",loanId:" + loanId);
		try {
			realNameAuthenticationResponse = carrierApi.getRealNameAuthentication(map).execute();
			realNameAuthentication = realNameAuthenticationResponse.body();
			MarvelsLogUtil.getInstance().info("===================魔蝎用户手机号是否实名认证请求返回,mobile" + mobile + ",loanId:" + loanId);

			status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
			apiResponse.setCode(RespStatus.SUCCESS.getCode());
			apiResponse.setMsg("魔蝎用户手机号是否实名认证查询成功");

			if (null != realNameAuthentication) {
				apiResponse.setData(realNameAuthentication);
				apiResponse.setCode(RespStatus.SUCCESS.getCode());
				apiResponse.setMsg(realNameAuthentication.getErrorMsg());
				if (!realNameAuthentication.isSuccess()) {
					status = LocalStatus.CALL_SUCCESS.getCode(); // 调用成功但业务数据返回非成功状态
					apiResponse.setCode(RespStatus.REQ_ERROR.getCode());
					apiResponse.setMsg(realNameAuthentication.getErrorMsg());
					MarvelsLogUtil.getInstance().info("魔蝎查询用户手机号是否实名认证请求异常,loanId" + loanId);
				}
				try {
					MarvelsLogUtil.getInstance().info("===================魔蝎用户手机号是否实名认证请求落库开始,mobile" + mobile + ",loanId:" + loanId);
					tradeNo = realNameAuthentication.getData().getTradeNo();
					IntMxMobileAuthentication intMxMobileAuthentication = new IntMxMobileAuthentication();
					intMxMobileAuthentication.setCreatedBy("sys");
					intMxMobileAuthentication.setCreatedDate(new Date());
					intMxMobileAuthentication.setDescript(realNameAuthentication.getData().getDesc());
					intMxMobileAuthentication.setLoanId(loanId);
					intMxMobileAuthentication.setResult(realNameAuthentication.getData().getCode());
					intMxMobileAuthentication.setTradeNo(realNameAuthentication.getData().getTradeNo());
					intMxMobileAuthentication.setUpdatedBy("sys");
					intMxMobileAuthentication.setUpdatedDate(new Date());
					intMxMobileAuthenticationMapper.insertSelective(intMxMobileAuthentication);
					MarvelsLogUtil.getInstance().info("===================魔蝎用户手机号是否实名认证请求结束,mobile" + mobile + ",loanId:" + loanId);

				} catch (Exception e) {
					status = LocalStatus.IN_DATABASE_FAIL.getCode(); // 查询成功，但是落库失败
					apiResponse.setCode(RespStatus.DATABASE_ERROR.getCode());
					apiResponse.setMsg("魔蝎用户手机号是否实名认证数据存库失败");
					MarvelsLogUtil.getInstance().error("魔蝎用户手机号是否实名认证数据存库失败,loanId" + loanId, e);
				}
			} else {
				status = LocalStatus.SUCCESS_WITHOUT_DATA.getCode(); // 查询成功但无数据
				MarvelsLogUtil.getInstance().info("魔蝎用户手机号是否实名认证返回数据为空,loanId:" + loanId);
				apiResponse.setCode(RespStatus.NODATA.getCode());
				apiResponse.setMsg("魔蝎查询用户手机号是否实名认证结果null");
			}

		} catch (Exception e) {
			status = LocalStatus.REQUEST_FAIL.getCode(); // 请求异常了，将状态置为请求失败
			apiResponse.setCode(RespStatus.REQ_ERROR.getCode());
			apiResponse.setMsg("魔蝎查询用户手机号是否实名认证请求异常");
			MarvelsLogUtil.getInstance().error("魔蝎查询用户手机号是否实名认证请求异常,loanId" + loanId, e);
		}
		
		String resultLog = "";
		if (apiResponse.getCode() == RespStatus.SUCCESS.getCode()
				|| apiResponse.getCode() == RespStatus.DATABASE_ERROR.getCode()) {
			resultLog = "1";
		} else if (apiResponse.getCode() == RespStatus.NODATA.getCode()) {
			resultLog = "0";
		} else {
			resultLog = "-1";
		}
		saveCallCountLog(loanId, ThirdMethodConstants.MX0006, resultLog, ThirdProductChannelConstant.MOXIE.getCode(),
				"魔蝎查询用户手机号是否实名认证");
		// 记入统一日志表
		saveDataQueryLogNew(tradeNo, loanId, mobile, sTime, ThirdMethodConstants.MX0006, thirdCode, status,
				"int_mx_data_query_log", null);
		return apiResponse;
	}

	@Override
	public MoxieTaskInfo searchCarrierStatus(String loanId) {
		MarvelsLogUtil.getInstance().info("==========查询运营商认证状态开始,loanId:" + loanId);
		if (StringUtils.isEmpty(loanId)) {
			return null;
		}
		MoxieTaskInfo moxieTaskInfo = new MoxieTaskInfo();
		moxieTaskInfo = moxieTaskInfoMapper.searchCarrierStatus(loanId);
		return moxieTaskInfo;
	}

	@Override
	public boolean taskIdStatusIsFail(String taskId) {
		Response<TaskStatusRsp> taskStatusRspResponse;
		MarvelsLogUtil.getInstance().info("============查询任务状态开始,taskId" + taskId);
		CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
		try {
			taskStatusRspResponse = carrierApi.getTaskStatus(taskId).execute();
			if (taskStatusRspResponse.isSuccessful()) {
				TaskStatusRsp taskStatusRsp = taskStatusRspResponse.body();
				String description = taskStatusRsp.getDescription();
				String phase = taskStatusRsp.getPhase();
				String phaseStatus = taskStatusRsp.getPhaseStatus();
				MarvelsLogUtil.getInstance().info(String.format("%s [%s] - %s", phase, phaseStatus, description + ",taskId" + taskId));

				if (phaseStatus.equals("DONE_FAIL") || phaseStatus.equals("DONE_TIMEOUT")) {
					MarvelsLogUtil.getInstance().info("任务失败/超时,taskId" + taskId);
					return true;
				}

			} else {
				int statusCode = taskStatusRspResponse.code();
				MarvelsLogUtil.getInstance().info("任务状态查询失败," + "status:" + statusCode + "\n" + taskStatusRspResponse.errorBody().string()
						+ "\n");
			}
			Thread.sleep(5000);// 休眠5秒
		} catch (Exception e1) {
			MarvelsLogUtil.getInstance().error("出现异常", e1);
		}

		return false;
	}

	/**
	 * 
	 * @Title: createCarrierTaskForMall @Description:
	 * 创建运营商数据任务(商城用) @param: @return: MoxieResponse @throws
	 */
	@Override
	public MoxieResponse createCarrierTaskForMall(Map<String, String> map) {

		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		MarvelsLogUtil.getInstance().info("===============>>>>创建任务开始时间" + DateUtil.dataFormat());
		String loanId = map.get("loanId");// 进件单号
		String orderNumber = map.get("orderNumber");// 订单号
		MoxieResponse moxieResponse = new MoxieResponse();
		TaskCreateReq req = TaskCreateReq.builder().add(ParamName.USER_ID, map.get("user_id"))
				.add(ParamName.ACCOUNT, map.get("mobile")).add(ParamName.PASSWORD, map.get("password"))
				.add(ParamName.ORIGIN, "2").add(ParamName.REAL_NAME, map.get("realName"))
				.add(ParamName.ID_CARD, map.get("idNumber")).build();
		String taskId = "";
		Response<TaskCreateRsp> taskCreateRspResponse = null;
		try {
			CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
			MarvelsLogUtil.getInstance().info("===============>>>>创建任务请求时间" + DateUtil.dataFormat());
			taskCreateRspResponse = carrierApi.createTask(req).execute();
			MarvelsLogUtil.getInstance().info("===============>>>>创建任务响应时间" + DateUtil.dataFormat());
			if (!taskCreateRspResponse.isSuccessful()) {
				MarvelsLogUtil.getInstance().info("==========>>>任务创建失败");
				MarvelsLogUtil.getInstance().info("==========>>>status:" + taskCreateRspResponse.code());
				MarvelsLogUtil.getInstance().info("==========>>>手机号码:" + map.get("mobile") + ",创建任务:"
						+ taskCreateRspResponse.errorBody().string());
				moxieResponse.setCode(-1);
				moxieResponse.setMsg(taskCreateRspResponse.errorBody().string());
				return moxieResponse;
			}

			boolean isTaskDone = false;
			// Step2 轮询状态
			long pollEndTime = System.currentTimeMillis() + thirdProperties.getPolling_time(); // 轮询最多3分钟
			taskId = taskCreateRspResponse.body().getTaskId();
			while (true) {
				MarvelsLogUtil.getInstance().info("===============>>>>查询状态时间" + DateUtil.dataFormat());
				Response<TaskStatusRsp> taskStatusRspResponse = carrierApi.getTaskStatus(taskId).execute();
				MarvelsLogUtil.getInstance().info("===============>>>>查询状态响应时间" + DateUtil.dataFormat());
				if (taskStatusRspResponse.isSuccessful()) {
					TaskStatusRsp taskStatusRsp = taskStatusRspResponse.body();
					String description = taskStatusRsp.getDescription();
					String phase = taskStatusRsp.getPhase();
					String phaseStatus = taskStatusRsp.getPhaseStatus();
					boolean finished = taskStatusRsp.isFinished();

					MarvelsLogUtil.getInstance().info("==========>>>手机号:" + map.get("mobile") + ",错误信息"
							+ String.format("%s [%s] - %s", phase, phaseStatus, description));

					if (phaseStatus.equals("WAIT_CODE")) {
						String inputType = taskStatusRsp.getInput().getType();
						System.out.println("等待用户输入,类型:" + inputType);
						if (taskStatusRsp.getInput().getType().equalsIgnoreCase("img")) {// 图片
							MarvelsLogUtil.getInstance().info(
									"=========>>>>base64在线转图片,访问 http://codebeautify.org/base64-to-image-converter");
							MarvelsLogUtil.getInstance().info("==========>>>手机号码:" + map.get("mobile") + "识别图片验证码:"
									+ taskStatusRsp.getInput().getValue());
							isTaskDone = true;
							moxieResponse.setImg(true);
							moxieResponse.setCode(1);
							moxieResponse.setTaskId(taskId);
							moxieResponse.setBase64Img(taskStatusRsp.getInput().getValue());
							break;
						} else {// 短信
							isTaskDone = true;
							moxieResponse.setSmsCode(true);
							moxieResponse.setCode(1);
							moxieResponse.setTaskId(taskId);
							MarvelsLogUtil.getInstance().info("==========>>>手机号码:" + map.get("mobile") + "输入类型为验证码:");
							break;
						}
					}

					if (phaseStatus.equals("DONE_FAIL") || phaseStatus.equals("DONE_TIMEOUT")) {
						moxieResponse.setCode(-1);
						moxieResponse.setMsg(description);
						MarvelsLogUtil.getInstance().info("==========>>>手机号码:" + map.get("mobile") + "输入类型为验证码:");
						break;
					}

					if ((taskStatusRsp.isCanLeave() && !phaseStatus.equals("DONE_FAIL")
							&& !phaseStatus.equals("DONE_TIMEOUT")) || (phaseStatus.equals("DONE_SUCC") && finished)) {
						System.out.println("任务已完成");
						isTaskDone = true;
						// 查询数据及落地
						Map<String, String> dataMap = new HashMap<String, String>();
						dataMap.put("task_id", taskId);
						dataMap.put("loanId", loanId);
						dataMap.put("orderNumber", orderNumber);
						dataMap.put("mobile", map.get("mobile"));
						MoXieCarrierForMall moXieCarrierForMall = new MoXieCarrierForMall();
						moXieCarrierForMall.startMoxieTask(dataMap);
						moxieResponse.setCode(0);
						moxieResponse.setTaskId(taskId);
						moxieResponse.setMsg("魔蝎运营商任务创建成功");
						break;

					}

				} else {
					System.out.println("任务状态查询失败");
					int statusCode = taskCreateRspResponse.code();
					System.out.println("status:" + statusCode + "\n");
					System.out.println(taskCreateRspResponse.errorBody().string() + "\n");
					moxieResponse.setCode(-1);
					moxieResponse.setMsg(taskCreateRspResponse.errorBody().string());
					return moxieResponse;
				}

				Thread.sleep(2000);
				if (System.currentTimeMillis() > pollEndTime) {
					moxieResponse.setCode(-1);
					moxieResponse.setMsg("魔蝎运营商任务创建超时");
					break;
				}
			}

		} catch (Exception e1) {
			MarvelsLogUtil.getInstance().error("==========>>>魔蝎创建运营商任务时:", e1);
			moxieResponse.setCode(-2);
			moxieResponse.setMsg("魔蝎运营商任务创建异常");
			return moxieResponse;
		}
		MarvelsLogUtil.getInstance().info("===============>>>>查询运营商结束时间" + DateUtil.dataFormat());
		return moxieResponse;

	}
	
	
	@Override
	public MoxieResponse createMoxieTask(Map<String, String> map) {
		MoxieResponse moxieResponse = new MoxieResponse();
		String taskId = map.get("taskId");
		String loanId = map.get("loanId");
		String mobile = map.get("mobile");
		if(StrUtil.hasEmpty(taskId, loanId, mobile)){
			moxieResponse.setCode(-1);
			moxieResponse.setMsg("魔蝎任务创建失败，必要参数缺失");
		}
		
		List<Object> degreeIds = EnumUtil.getFieldValues(MoXieTaskType.class, "type");
		if(StrUtil.isEmpty(map.get("type")) || !degreeIds.contains(Integer.parseInt(map.get("type")))){
			moxieResponse.setCode(-1);
			moxieResponse.setMsg("魔蝎任务创建失败，类型不符");
		}
		
		
		MoxieTaskInfo moxieTaskInfo=new MoxieTaskInfo();
		moxieTaskInfo.setCreatedBy("sys");
		moxieTaskInfo.setCreatedDate(new Date());
		moxieTaskInfo.setLoanId(loanId);
		moxieTaskInfo.setTaskId(taskId);
		moxieTaskInfo.setMobile(mobile);
		moxieTaskInfo.setType(map.get("type"));
		moxieTaskInfo.setResult("0");
		Integer type = Integer.parseInt(map.get("type"));
		if(type == MoXieTaskType.ALIPAY.getType()){
			/*MoxieAlipayThread moxieAlipayThread = new MoxieAlipayThread();
			moxieAlipayThread.setMap(map);
			Thread thread = new Thread(moxieAlipayThread);
			thread.start();*/
			moxieResponse.setCode(0);
			moxieResponse.setTaskId(taskId);
			moxieResponse.setMsg("魔蝎支付宝任务创建成功");
		}else if(type == MoXieTaskType.CARRIER.getType()){
			/*map.put("task_id", taskId);
			MoXieCarrierThread moXieCarrierThread = new MoXieCarrierThread();
			moXieCarrierThread.setMap(map);
			Thread thread = new Thread(moXieCarrierThread);
			thread.start();*/
			moxieResponse.setCode(0);
			moxieResponse.setTaskId(taskId);
			moxieResponse.setMsg("魔蝎运营商任务创建成功");
		}else if(type == MoXieTaskType.FUND.getType()){
			/*MoxieFundThread moxieFundThread = new MoxieFundThread();
			moxieFundThread.setMap(map);
			Thread thread = new Thread(moxieFundThread);
			thread.start();*/
			moxieResponse.setCode(0);
			moxieResponse.setTaskId(taskId);
			moxieResponse.setMsg("魔蝎公积金任务创建成功");
		}
		moxieTaskInfoMapper.insertMoxieTaskInfo(moxieTaskInfo);
		return moxieResponse;
	}
	
	
	@Override
	public ApiResponse<MXAlipayReport> alipayReportV6(String mobile, String taskId, String serialNum,
			String loanId, String channel) {
		ApiResponse<MXAlipayReport> apiResponse = new ApiResponse<MXAlipayReport>();
		if (PropertiesUtils.isTurnOffForSwitch("switch.mx0007")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			apiResponse.setCode(RespStatus.DISABLE.getCode());
			apiResponse.setMsg(RespStatus.DISABLE.getMsg());
			return apiResponse;
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		String url = ThirdPropertiesInitUtil.getThirdProperties().getMx_baseUrl();
		MoxieApiFactory apiFactory = MoxieApiFactory.builder().withAuthToken(new AuthToken(ThirdPropertiesInitUtil.getThirdProperties().getMx_api_key(), ThirdPropertiesInitUtil.getThirdProperties().getMx_token()))
				.withBaseUrl(url).build();
		CarrierApi carrierApi = apiFactory.newApi(CarrierApi.class);
		Response<MXAlipayReport> alipayReportResponse = null;
		Date eTime = new Date();
		MXAlipayReport mxAlipayReport = null;
		String method = ThirdMethodConstants.MX0007;
		MarvelsLogUtil.getInstance().info("===================魔蝎支付宝数据获取用户报告v6请求参数: taskId" + taskId + ",mobile+" + mobile
				+ ",loanId:" + loanId);
		try {

			alipayReportResponse = carrierApi.getAlipayReportV6(taskId).execute();
			mxAlipayReport = alipayReportResponse.body();
			MarvelsLogUtil.getInstance().info("===================魔蝎支付宝数据获取用户报告v6请求返回,mobile" + mobile + ",loanId:" + loanId);

			status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
			apiResponse.setCode(RespStatus.SUCCESS.getCode());
			apiResponse.setMsg("魔蝎查询支付宝报告成功");

			if (null != mxAlipayReport) {
				MarvelsLogUtil.getInstance().info("返回数据不为空,loanId:" + loanId);
				try {
					
					String message = null;
					//获取用户报告message
					try {
						MarvelsLogUtil.getInstance().info("魔蝎支付宝数据获取用户报告message信息,loan[" + loanId + "]");
						Response<MXUserReportCall> userReportCallResponse = carrierApi.getUserReportInfo(taskId, "report").execute();
						MarvelsLogUtil.getInstance().info("魔蝎支付宝数据用户报告message信息,loan[" + loanId + "],响应信息：" + com.alibaba.fastjson.JSONObject.toJSONString(userReportCallResponse));
						MXUserReportCall mxUserReportCall = userReportCallResponse.body();
						if(null != mxUserReportCall && mxUserReportCall.getResult()){
							message = mxUserReportCall.getMessage();
						}
						MarvelsLogUtil.getInstance().info("魔蝎支付宝数据获取用户报告message信息完成,loan[" + loanId + "]");
					} catch (Exception e) {
						MarvelsLogUtil.getInstance().error("魔蝎支付宝数据获取用户报告message信息异常,loan[" + loanId + "]", e);
					}
					
					MarvelsLogUtil.getInstance().info("===================魔蝎支付宝数据获取用户报告v6请求落库开始,mobile" + mobile + ",loanId:" + loanId);
					dGMoXieService.alipayReportV6(mxAlipayReport, serialNum, loanId, message);
					apiResponse.setData(mxAlipayReport);
					MarvelsLogUtil.getInstance().info("===================魔蝎支付宝数据获取用户报告v6请求结束,mobile" + mobile + ",loanId:" + loanId);
				} catch (Exception e) {
					status = LocalStatus.IN_DATABASE_FAIL.getCode(); // 查询成功，但是落库失败
					apiResponse.setCode(RespStatus.DATABASE_ERROR.getCode());
					apiResponse.setMsg("魔蝎查询支付宝报告v6数据存库失败");
					MarvelsLogUtil.getInstance().error(">>>>>>>>魔蝎查询支付宝报告v6数据存库失败:loanId:" + loanId, e);
				}
			} else {
				status = LocalStatus.SUCCESS_WITHOUT_DATA.getCode(); // 查询成功但无数据
				MarvelsLogUtil.getInstance().info("返回数据为空");
				MarvelsLogUtil.getInstance().info("=============>>>>查询支付宝报告,loanId:" + loanId + ",taskId:" + taskId + ",mobile"
						+ mobile);
				apiResponse.setCode(RespStatus.NODATA.getCode());
				apiResponse.setMsg("魔蝎查询支付宝报告为null");
			}

		} catch (IOException e) {
			status = LocalStatus.REQUEST_FAIL.getCode(); // 请求异常了，将状态置为请求失败

			apiResponse.setCode(RespStatus.REQ_ERROR.getCode());
			apiResponse.setMsg("魔蝎查询支付宝报告请求异常");
			MarvelsLogUtil.getInstance().error("魔蝎查询支付宝报告v6请求异常,loanId" + loanId, e);

		}
		Date sTime = new Date();
		String reqBody = "手机号码：" + mobile + "，任务Id:" + taskId;
		if (apiResponse.getCode() != RespStatus.SUCCESS.getCode()) {
			saveErrorLog(serialNum, Integer.toString(apiResponse.getCode()), apiResponse.getMsg(), reqBody,
					"", channel, method, sTime, eTime);
		}
		saveLog(serialNum, Integer.toString(apiResponse.getCode()), apiResponse.getMsg(), reqBody,
				alipayReportResponse.toString(), channel, method, sTime, eTime, "", "");

		String resultLog = "";
		if (apiResponse.getCode() == RespStatus.SUCCESS.getCode()
				|| apiResponse.getCode() == RespStatus.DATABASE_ERROR.getCode()) {
			resultLog = "1";
		} else if (apiResponse.getCode() == RespStatus.NODATA.getCode()) {
			resultLog = "0";
		} else {
			resultLog = "-1";
		}
		saveCallCountLog(loanId, ThirdMethodConstants.MX0007, resultLog, ThirdProductChannelConstant.MOXIE.getCode(),
				"魔蝎支付宝数据获取用户报告v6");
		// 记入统一日志表
		saveDataQueryLogNew(serialNum + "_" + ThirdMethodConstants.MX0007, loanId, mobile, sTime,
				ThirdMethodConstants.MX0007, thirdCode, status, "int_mx_data_query_log", null);
		return apiResponse;
	}

	
	@Override
	public ApiResponse<MXAlipayZmsReport> alipayZmsReportV2(String mobile, String taskId, String serialNum, String loanId,
			String channel) {
		ApiResponse<MXAlipayZmsReport> apiResponse = new ApiResponse<MXAlipayZmsReport>();
		if (PropertiesUtils.isTurnOffForSwitch("switch.mx0008")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			apiResponse.setCode(RespStatus.DISABLE.getCode());
			apiResponse.setMsg(RespStatus.DISABLE.getMsg());
			return apiResponse;
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		String url = ThirdPropertiesInitUtil.getThirdProperties().getMx_baseUrl();
		MoxieApiFactory apiFactory = MoxieApiFactory.builder().withAuthToken(new AuthToken(ThirdPropertiesInitUtil.getThirdProperties().getMx_api_key(), ThirdPropertiesInitUtil.getThirdProperties().getMx_token()))
				.withBaseUrl(url).build();
		CarrierApi carrierApi = apiFactory.newApi(CarrierApi.class);
		Response<MXAlipayZmsReport> alipayZmsReportResponse = null;
		Date eTime = new Date();
		MXAlipayZmsReport mxAlipayZmsReport = null;
		String method = ThirdMethodConstants.MX0008;
		MarvelsLogUtil.getInstance().info("===================魔蝎支付宝芝麻分数据获取用户报告v2请求参数: taskId" + taskId + ",mobile+" + mobile
				+ ",loanId:" + loanId);
		try {

			alipayZmsReportResponse = carrierApi.getAlipayZmsReportV2(taskId).execute();
			mxAlipayZmsReport = alipayZmsReportResponse.body();
			MarvelsLogUtil.getInstance().info("===================魔蝎支付宝芝麻分数据获取用户报告v2请求返回,mobile" + mobile + ",loanId:" + loanId);

			status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
			apiResponse.setCode(RespStatus.SUCCESS.getCode());
			apiResponse.setMsg("魔蝎查询支付宝芝麻分报告成功");

			if (null != mxAlipayZmsReport) {
				MarvelsLogUtil.getInstance().info("返回数据不为空,loanId:" + loanId);
				try {
					MarvelsLogUtil.getInstance().info("===================魔蝎支付宝芝麻分数据获取用户报告v2请求落库开始,mobile" + mobile + ",loanId:" + loanId);
					dGMoXieService.alipayZmsReportV2(mxAlipayZmsReport, serialNum, loanId);
					apiResponse.setData(mxAlipayZmsReport);
					MarvelsLogUtil.getInstance().info("===================魔蝎支付宝芝麻分数据获取用户报告v2请求结束,mobile" + mobile + ",loanId:" + loanId);
				} catch (Exception e) {
					status = LocalStatus.IN_DATABASE_FAIL.getCode(); // 查询成功，但是落库失败
					apiResponse.setCode(RespStatus.DATABASE_ERROR.getCode());
					apiResponse.setMsg("魔蝎查询支付宝芝麻分报告v2数据存库失败");
					MarvelsLogUtil.getInstance().error(">>>>>>>>魔蝎查询支付宝芝麻分报告v2数据存库失败:loanId:" + loanId, e);
				}
			} else {
				status = LocalStatus.SUCCESS_WITHOUT_DATA.getCode(); // 查询成功但无数据
				MarvelsLogUtil.getInstance().info("返回数据为空");
				MarvelsLogUtil.getInstance().info("=============>>>>查询支付宝芝麻分报告,loanId:" + loanId + ",taskId:" + taskId + ",mobile"
						+ mobile);
				apiResponse.setCode(RespStatus.NODATA.getCode());
				apiResponse.setMsg("魔蝎查询支付宝芝麻分报告为null");
			}

		} catch (IOException e) {
			status = LocalStatus.REQUEST_FAIL.getCode(); // 请求异常了，将状态置为请求失败

			apiResponse.setCode(RespStatus.REQ_ERROR.getCode());
			apiResponse.setMsg("魔蝎查询支付宝芝麻分报告请求异常");
			MarvelsLogUtil.getInstance().error("魔蝎查询支付宝芝麻分报告v2请求异常,loanId" + loanId, e);

		}
		Date sTime = new Date();
		String reqBody = "手机号码：" + mobile + "，任务Id:" + taskId;
		if (apiResponse.getCode() != RespStatus.SUCCESS.getCode()) {
			saveErrorLog(serialNum, Integer.toString(apiResponse.getCode()), apiResponse.getMsg(), reqBody,
					"", channel, method, sTime, eTime);
		}
		saveLog(serialNum, Integer.toString(apiResponse.getCode()), apiResponse.getMsg(), reqBody,
				alipayZmsReportResponse.toString(), channel, method, sTime, eTime, "", "");

		String resultLog = "";
		if (apiResponse.getCode() == RespStatus.SUCCESS.getCode()
				|| apiResponse.getCode() == RespStatus.DATABASE_ERROR.getCode()) {
			resultLog = "1";
		} else if (apiResponse.getCode() == RespStatus.NODATA.getCode()) {
			resultLog = "0";
		} else {
			resultLog = "-1";
		}
		saveCallCountLog(loanId, ThirdMethodConstants.MX0008, resultLog, ThirdProductChannelConstant.MOXIE.getCode(),
				"魔蝎支付宝芝麻分数据获取用户报告v2");
		// 记入统一日志表
		saveDataQueryLogNew(serialNum + "_" + ThirdMethodConstants.MX0008, loanId, mobile, sTime,
				ThirdMethodConstants.MX0008, thirdCode, status, "int_mx_data_query_log", null);
		return apiResponse;
	}
	
	/**
	 * 
	 * @Title:
	 * getCarrierTaskStatus @Description:查询魔蝎运营商数据查询情况（商城用） @param: @return:
	 * String @throws
	 */
	@Override
	public String getCarrierTaskStatus(String loanId) {
		MoXieCarrierForMall moXieCarrierForMall = new MoXieCarrierForMall();
		return moXieCarrierForMall.getMoXieTaskResult(loanId);
	}

	/**
	 * 
	 * @Title: verifySMSCodeForMall @Description: 验证魔蝎验证码（商城用） @param: @return:
	 * MoxieResponse @throws
	 */
	@Override
	public MoxieResponse verifySMSCodeForMall(Map<String, String> map) {

		MarvelsLogUtil.getInstance().info("===============>>>>验证短信验证码开始时间" + DateUtil.dataFormat());
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		String loanId = map.get("loanId");// 进件单号
		String orderNumber = map.get("orderNumber");// 订单号
		String name = map.get("name");
		String idcard = map.get("idcard");
		MoxieResponse moxieResponse = new MoxieResponse();
		NumberReport numberReport = new NumberReport();
		String taskId = map.get("taskId");
		String code = map.get("code");
		String accumulationFund = map.get("accumulationFund");
		Map<String, String> responseMap = new HashMap<String, String>();
		// responseMap.put("userId", cid);
		CarrierApi carrierApi = this.getMoxieApiFactory().newApi(CarrierApi.class);
		UserInput input = new UserInput(code);
		try {
			MarvelsLogUtil.getInstance().info("===============>>>>验证短信验证码请求时间" + DateUtil.dataFormat());
			Response<TaskVoidRsp> taskVoidRsp = carrierApi.input(taskId, input).execute();
			MarvelsLogUtil.getInstance().info("===============>>>>验证短信验证码结束时间" + DateUtil.dataFormat());
			if (!taskVoidRsp.isSuccessful()) {
				MarvelsLogUtil.getInstance().info("==========>>>校验验证码" + taskVoidRsp.errorBody().string());
				moxieResponse.setCode(-1);
				moxieResponse.setMsg(taskVoidRsp.errorBody().string());
				return moxieResponse;
			}
			boolean isTaskDone = false;
			// Step2 轮询状态
			long pollEndTime = System.currentTimeMillis() + thirdProperties.getPolling_time(); // 轮询最多3分钟
			while (true) {
				MarvelsLogUtil.getInstance().info("===============>>>>任务状态查询开始时间" + DateUtil.dataFormat());
				Response<TaskStatusRsp> taskStatusRspResponse = carrierApi.getTaskStatus(taskId).execute();
				MarvelsLogUtil.getInstance().info("===============>>>>任务状态查询结束时间" + DateUtil.dataFormat());
				if (taskStatusRspResponse.isSuccessful()) {
					TaskStatusRsp taskStatusRsp = taskStatusRspResponse.body();
					String description = taskStatusRsp.getDescription();
					String phase = taskStatusRsp.getPhase();
					String phaseStatus = taskStatusRsp.getPhaseStatus();
					boolean finished = taskStatusRsp.isFinished();
					System.out.println(String.format("%s [%s] - %s", phase, phaseStatus, description));

					if (phaseStatus.equals("WAIT_CODE")) {
						String inputType = taskStatusRsp.getInput().getType();
						MarvelsLogUtil.getInstance().info("==========>>>进件单号:" + loanId + ",等待用户输入,类型:" + inputType);
						if (taskStatusRsp.getInput().getType().equalsIgnoreCase("img")) {// 图片
							MarvelsLogUtil.getInstance().info(
									"=========>>>>base64在线转图片,访问 http://codebeautify.org/base64-to-image-converter");
							MarvelsLogUtil.getInstance().info("=========>>>>请识别图片验证码:" + taskStatusRsp.getInput().getValue());
							isTaskDone = true;
							moxieResponse.setImg(true);
							moxieResponse.setCode(1);
							moxieResponse.setBase64Img(taskStatusRsp.getInput().getValue());
							break;
						} else {// 短信
							isTaskDone = true;
							moxieResponse.setSmsCode(true);
							moxieResponse.setCode(1);
							break;
						}
					}
					if (phaseStatus.equals("DONE_FAIL") || phaseStatus.equals("DONE_TIMEOUT")) {
						moxieResponse.setCode(-1);
						moxieResponse.setMsg(description);
						MarvelsLogUtil.getInstance().info("==========>>>进件单号:" + loanId + "任务失败/超时");
						break;
					}
					if ((taskStatusRsp.isCanLeave() && !phaseStatus.equals("DONE_FAIL")
							&& !phaseStatus.equals("DONE_TIMEOUT")) || (phaseStatus.equals("DONE_SUCC") && finished)) {
						MarvelsLogUtil.getInstance().info("==========>>>进件单号:" + loanId + "任务已完成");
						isTaskDone = true;

						Map<String, String> dataMap = new HashMap<String, String>();
						dataMap.put("task_id", taskId);
						dataMap.put("loanId", loanId);
						dataMap.put("orderNumber", orderNumber);
						dataMap.put("mobile", map.get("mobile"));
						MoXieCarrierForMall moXieCarrierForMall = new MoXieCarrierForMall();
						moXieCarrierForMall.startMoxieTask(dataMap);
						moxieResponse.setCode(0);
						moxieResponse.setTaskId(taskId);
						moxieResponse.setMsg("魔蝎运营商任务创建成功");

						break;

					}

				} else {
					MarvelsLogUtil.getInstance().info(taskStatusRspResponse.errorBody().string());
					int statusCode = taskStatusRspResponse.code();
					MarvelsLogUtil.getInstance().info("status:" + statusCode + "\n");
					MarvelsLogUtil.getInstance().info("==========>>>进件单号:" + loanId + ",错误信息" + taskStatusRspResponse.errorBody().string()
							+ "\n");
					moxieResponse.setCode(-1);
					moxieResponse.setMsg(taskStatusRspResponse.errorBody().string());
					return moxieResponse;
				}

				Thread.sleep(2000);
				if (System.currentTimeMillis() > pollEndTime) {
					moxieResponse.setCode(-1);
					moxieResponse.setMsg("魔蝎运营商任务创建超时");
					break;
				}
			}

		} catch (Exception e1) {
			MarvelsLogUtil.getInstance().error("==========>>>进件单号:" + loanId + ",错误信息", e1);
			moxieResponse.setCode(-2);
			moxieResponse.setMsg("魔蝎运营商任务创建异常");
			return moxieResponse;
		}

		MarvelsLogUtil.getInstance().info("===============>>>>验证短信验证码结束 时间" + DateUtil.dataFormat());
		return moxieResponse;

	}

	@Override
	public Map<String, Object> queryMxDataInfo(Map<String, String> map) {
		String serialNum = map.get("serialNum");
		String dataType = map.get("dataType");
		String dataTypeTwo = map.get("dataTypeTwo");
		Map<String, Object> dataMap = new HashMap<>();

		List<IntMxDataUsageDetails> intMxDataUsageDetails = moXieDataInfoMapper.searchDataUsageDetails(serialNum);// moxieObtainAllDataDetails
		List<IntMxSmsDetails> intMxSmsDetails = moXieDataInfoMapper.searchSmsDetails(serialNum);// moxieObtainAllDataDetails
		List<IntMxUserInfo> intMxUserInfo = moXieDataInfoMapper.searchMxUserInfo(serialNum);// 未使用，无数据
		List<IntMxBillRecord> intMxBillRecord = moXieDataInfoMapper.searchMxBillRecord(serialNum);// 未使用，无数据
		List<IntMxLoanInfo> intMxLoanInfo = moXieDataInfoMapper.searchMxLoanInfo(serialNum);// 未使用，无数据
		List<IntMxLoanRepayRecord> intMxLoanRepayRecord = moXieDataInfoMapper.searchLoanRepayRecord(serialNum);// 未使用，无数据
		List<IntMxCallDetails> intMxCallDetails = moXieDataInfoMapper.searchMxCallDetails(serialNum);// moxieObtainAllDataDetails
		List<IntMxBillsMonth> intMxBillsMonth = moXieDataInfoMapper.searchMxBillsMonth(serialNum);// moxieObtainAllDataDetails
		List<IntMxPackageItems> intMxPackageItems = moXieDataInfoMapper.searchPackageItems(serialNum);// moxieObtainAllDataDetails
		List<IntMxPackageInfo> intMxPackageInfo = moXieDataInfoMapper.searchPackageInfo(serialNum);// moxieObtainAllDataDetails
		List<IntMxUserBasicInfo> intMxUserBasicInfo = moXieDataInfoMapper.searchUserBasicInfo(serialNum);// moxieObtainUserMobileReport
		List<IntMxAccountBaseInfo> intMxAccountBaseInfo = moXieDataInfoMapper.searchAccountBaseInfo(serialNum);// moxieObtainAllDataDetails
		List<IntMxDataSource> intMxDataSource = moXieDataInfoMapper.searchMxDataSource(serialNum);// moxieObtainUserMobileReport
		List<IntMxBasicInfoCheckItems> intMxBasicInfoCheckItems = moXieDataInfoMapper
				.searchBasicInfoCheckItems(serialNum);// moxieObtainAllDataDetailsv2
		List<IntMxCallNumTop3> intMxCallNumTop3 = moXieDataInfoMapper.searchCallNumTop3(serialNum, dataType);// moxieObtainUserMobileReport
		List<IntMxCallLocationTop3> intMxCallLocationTop3 = moXieDataInfoMapper.searchCallLocationTop3(serialNum,
				dataType);// moxieObtainUserMobileReport
		List<IntMxCallContactDetail> intMxCallContactDetail = moXieDataInfoMapper
				.searchCallContactDetail(serialNum);// moxieObtainUserMobileReport
		List<IntMxRiskAnalysis> intMxRiskAnalysis = moXieDataInfoMapper.searchRiskAnalysis(serialNum);// moxieObtainUserMobileReport
		List<IntMxRiskCheckItem> intMxRiskCheckItem = moXieDataInfoMapper.searchRiskCheckItem(serialNum);// moxieObtainUserMobileReport
		List<IntMxActiveDegress> intMxActiveDegress = moXieDataInfoMapper.searchActiveDegress(serialNum);// moxieObtainUserMobileReport
		List<IntMxConsumptionAnalysis> intMxConsumptionAnalysis = moXieDataInfoMapper
				.searchConsumptionAnalysis(serialNum);// moxieObtainUserMobileReport
		List<IntMxCallAnalysis> intMxCallAnalysis = moXieDataInfoMapper.searchMxCallAnalysis(serialNum);// moxieObtainAllDataDetailsv2
		List<IntMxCallDurationDetail> intMxCallDurationDetail = moXieDataInfoMapper
				.searchCallDurationDetail(serialNum, dataType);// moxieObtainUserMobileReport
		List<IntMxCallLocationDetail> intMxCallLocationDetail = moXieDataInfoMapper
				.searchCallLocationDetail(serialNum, dataType);// moxieObtainUserMobileReport
		List<IntMxCallTimeDetail> intMxCallTimeDetail = moXieDataInfoMapper.searchCallTimeDetail(serialNum);// moxieObtainUserMobileReport
		List<IntMxCallThirdPartyDetail> intMxCallThirdPartyDetail = moXieDataInfoMapper
				.searchCallThirdPartyDetail(serialNum);// moxieObtainUserMobileReport
		List<IntMxCallFamilyDetail> intMxCallFamilyDetail = moXieDataInfoMapper.searchCallFamilyDetail(serialNum);// moxieObtainUserMobileReport
		List<IntMxActiveDegreeDetail> intMxActiveDegreeDetail = moXieDataInfoMapper
				.searchActiveDegreeDetail(serialNum);// moxieObtainUserMobileReport
		List<IntMxConsumptionDetail> intMxConsumptionDetail = moXieDataInfoMapper
				.searchConsumptionDetail(serialNum);// moxieObtainUserMobileReport
		List<IntMxCallLocal6m> intMxCallLocal6m = moXieDataInfoMapper.searchCallLocal6m(serialNum);// moxieObtainAllDataDetails
		List<IntMxCallMobile6m> intMxCallMobile6m = moXieDataInfoMapper.searchCallMobile6m(serialNum);// moxieObtainAllDataDetails
		dataMap.put("intMxDataUsageDetails", intMxDataUsageDetails);
		dataMap.put("intMxSmsDetails", intMxSmsDetails);
		dataMap.put("intMxUserInfo", intMxUserInfo);
		dataMap.put("intMxBillRecord", intMxBillRecord);
		dataMap.put("intMxLoanInfo", intMxLoanInfo);
		dataMap.put("intMxLoanRepayRecord", intMxLoanRepayRecord);
		dataMap.put("intMxCallDetails", intMxCallDetails);
		dataMap.put("intMxBillsMonth", intMxBillsMonth);
		dataMap.put("intMxPackageItems", intMxPackageItems);
		dataMap.put("intMxPackageInfo", intMxPackageInfo);
		dataMap.put("intMxUserBasicInfo", intMxUserBasicInfo);
		dataMap.put("intMxAccountBaseInfo", intMxAccountBaseInfo);
		dataMap.put("intMxDataSource", intMxDataSource);
		dataMap.put("intMxBasicInfoCheckItems", intMxBasicInfoCheckItems);
		dataMap.put("intMxCallNumTop3", intMxCallNumTop3);
		dataMap.put("intMxCallNumTop6", moXieDataInfoMapper.searchCallNumTop3(serialNum, dataTypeTwo));
		dataMap.put("intMxCallLocationTop3", intMxCallLocationTop3);
		dataMap.put("intMxCallLocationTop6", moXieDataInfoMapper.searchCallLocationTop3(serialNum, dataTypeTwo));
		dataMap.put("intMxCallContactDetail", intMxCallContactDetail);
		dataMap.put("intMxRiskAnalysis", intMxRiskAnalysis);
		dataMap.put("intMxRiskCheckItem", intMxRiskCheckItem);
		dataMap.put("intMxActiveDegress", intMxActiveDegress);
		dataMap.put("intMxConsumptionAnalysis", intMxConsumptionAnalysis);
		dataMap.put("intMxCallAnalysis", intMxCallAnalysis);
		dataMap.put("intMxCallDurationDetail3", intMxCallDurationDetail);
		dataMap.put("intMxCallDurationDetail6",
				moXieDataInfoMapper.searchCallDurationDetail(serialNum, dataTypeTwo));
		dataMap.put("intMxCallLocationDetail3", intMxCallLocationDetail);
		dataMap.put("intMxCallLocationDetail6",
				moXieDataInfoMapper.searchCallLocationDetail(serialNum, dataTypeTwo));
		dataMap.put("intMxCallTimeDetail", intMxCallTimeDetail);
		dataMap.put("intMxCallThirdPartyDetail", intMxCallThirdPartyDetail);
		dataMap.put("intMxCallFamilyDetail", intMxCallFamilyDetail);
		dataMap.put("intMxActiveDegreeDetail", intMxActiveDegreeDetail);
		dataMap.put("intMxConsumptionDetail", intMxConsumptionDetail);
		dataMap.put("intMxCallLocal6m", intMxCallLocal6m);
		dataMap.put("intMxCallMobile6m", intMxCallMobile6m);
		return dataMap;
	}

	/**
	 * 给bean赋值返回list
	 * 
	 * @param jsonArr
	 * @param obj
	 * @return
	 */
	public List<Object> getObjByJsonList(String jsonStr, Class obj) {
		List<Object> list = new ArrayList<Object>();
		if (isJsonArray(jsonStr)) {
			JSONArray jsonArr = JSONArray.fromObject(jsonStr);
			String strData0 = "";
			if (jsonArr != null && jsonArr.size() > 0) {
				for (int i = 0; i < jsonArr.size(); i++) {
					strData0 = jsonArr.get(i).toString();
					Object objRet = com.alibaba.fastjson.JSONObject.parseObject(strData0, obj);
					list.add(objRet);
				}
			}
		}
		return list;
	}

	/**
	 * 判断字符串是否可以转化为JSON数组
	 * 
	 * @param content
	 * @return
	 */
	public static boolean isJsonArray(String content) {
		if (StringUtils.isBlank(content))
			return false;
		StringUtils.isEmpty(content);
		try {
			JSONArray.fromObject(content);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public Map<String, Object> queryMxDataInfo(Map<String, String> map, String productType) {
		long start = System.currentTimeMillis();
		String timeStr = "mysql";
		MarvelsLogUtil.getInstance().info("查询魔蝎数据传入参数：" + map);
		String serialNum = map.get("serialNum");
		String dataType = map.get("dataType");
		String dataTypeTwo = map.get("dataTypeTwo");
		String loanId = map.get("loanId");
		Map<String, Object> dataMap = new HashMap<>();
		List<IntMxDataUsageDetails> intMxDataUsageDetails = new ArrayList<IntMxDataUsageDetails>();
		List<IntMxSmsDetails> intMxSmsDetails = new ArrayList<>();
		List<IntMxUserInfo> intMxUserInfo = new ArrayList<IntMxUserInfo>();
		List<IntMxBillRecord> intMxBillRecord = new ArrayList<IntMxBillRecord>();
		List<IntMxLoanInfo> intMxLoanInfo = new ArrayList<IntMxLoanInfo>();
		List<IntMxLoanRepayRecord> intMxLoanRepayRecord = new ArrayList<IntMxLoanRepayRecord>();
		List<IntMxCallDetails> intMxCallDetails = new ArrayList<>();
		List<IntMxBillsMonth> intMxBillsMonth = new ArrayList<>();
		List<IntMxPackageItems> intMxPackageItems = new ArrayList<>();
		List<IntMxPackageInfo> intMxPackageInfo = new ArrayList<>();
		List<IntMxUserBasicInfo> intMxUserBasicInfo = new ArrayList<>();
		List<IntMxAccountBaseInfo> intMxAccountBaseInfo = new ArrayList<>();
		List<IntMxDataSource> intMxDataSource = new ArrayList<>();
		List<IntMxBasicInfoCheckItems> intMxBasicInfoCheckItems = new ArrayList<>();
		List<IntMxCallContactDetail> intMxCallContactDetail = new ArrayList<>();
		List<IntMxRiskAnalysis> intMxRiskAnalysis = new ArrayList<>();
		List<IntMxRiskCheckItem> intMxRiskCheckItem = new ArrayList<>();
		List<IntMxActiveDegress> intMxActiveDegress = new ArrayList<>();
		List<IntMxConsumptionAnalysis> intMxConsumptionAnalysis = new ArrayList<>();
		List<IntMxCallAnalysis> intMxCallAnalysis = new ArrayList<>();
		List<IntMxCallTimeDetail> intMxCallTimeDetail = new ArrayList<>();
		List<IntMxCallThirdPartyDetail> intMxCallThirdPartyDetail = new ArrayList<>();
		List<IntMxCallFamilyDetail> intMxCallFamilyDetail = new ArrayList<>();
		List<IntMxActiveDegreeDetail> intMxActiveDegreeDetail = new ArrayList<>();
		List<IntMxConsumptionDetail> intMxConsumptionDetail = new ArrayList<>();
		List<IntMxCallLocal6m> intMxCallLocal6m = new ArrayList<>();
		List<IntMxCallMobile6m> intMxCallMobile6m = new ArrayList<>();
		List<IntMxRechargeItems> intMxRechargeItems = new ArrayList<>();
		List<IntMxCallNumTop3> intMxCallNumTop3 = new ArrayList<>();
		List<IntMxCallNumTop3> intMxCallNumTop6 = new ArrayList<>();// ok
		List<IntMxCallLocationTop3> intMxCallLocationTop3 = new ArrayList<>();
		List<IntMxCallLocationTop3> intMxCallLocationTop6 = new ArrayList<>();// ok
		List<IntMxCallDurationDetail> intMxCallDurationDetail = new ArrayList<>();
		List<IntMxCallDurationDetail> intMxCallDurationDetail6 = new ArrayList<>();// ok
		List<IntMxCallLocationDetail> intMxCallLocationDetail = new ArrayList<>();
		List<IntMxCallLocationDetail> intMxCallLocationDetail6 = new ArrayList<>();// ok
		if (ProductUtils.isRSHU(productType)) {
			// 转换信息
			try {
				intMxAccountBaseInfo = moXieDataInfoMapper.searchRongshuOperatorBasicInfo(loanId);
				intMxCallDetails = moXieDataInfoMapper.searchRongshuOperatorCallInfo(loanId);
				intMxRechargeItems = moXieDataInfoMapper.searchRongshuOperatorPaymentInfo(loanId);
				intMxBillsMonth = moXieDataInfoMapper.searchRongshuOperatorBillInfo(loanId);
				intMxUserBasicInfo = moXieDataInfoMapper.searchRongshuUserBasicInfo(loanId);
				intMxDataSource = moXieDataInfoMapper.searchRongshuMxDataSource(loanId);
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error("榕树获取运营商数据异常", e);
			}

		} else if (ProductUtils.isFANLI(productType)) {
			// 转换信息
			try {
				intMxAccountBaseInfo = moXieDataInfoMapper.searchFanLiOperatorBasicInfo(loanId);
				intMxUserBasicInfo = moXieDataInfoMapper.searchFanLiUserBasicInfo(loanId);
				intMxDataSource = moXieDataInfoMapper.searchFanLiMxDataSource(loanId);
				intMxBillsMonth = moXieDataInfoMapper.searchFanLiOperatorBillInfo(loanId);
				intMxCallDetails = moXieDataInfoMapper.searchFanLiOperatorCallInfo(loanId);
				intMxRechargeItems = moXieDataInfoMapper.searchFanLiOperatorPaymentInfo(loanId);
				intMxPackageInfo = moXieDataInfoMapper.searchFanLiPackageInfo(loanId);
				intMxPackageItems = moXieDataInfoMapper.searchFanLiPackageItems(loanId);
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error("返利网获取运营商数据异常", e);
			}
		} else {
			intMxDataUsageDetails = moXieDataInfoMapper.searchDataUsageDetails(serialNum);
			intMxSmsDetails = moXieDataInfoMapper.searchSmsDetails(serialNum);
			intMxUserInfo = moXieDataInfoMapper.searchMxUserInfo(serialNum);
			intMxBillRecord = moXieDataInfoMapper.searchMxBillRecord(serialNum);
			intMxLoanInfo = moXieDataInfoMapper.searchMxLoanInfo(serialNum);
			intMxLoanRepayRecord = moXieDataInfoMapper.searchLoanRepayRecord(serialNum);
			intMxCallDetails = moXieDataInfoMapper.searchMxCallDetails(serialNum);
			intMxBillsMonth = moXieDataInfoMapper.searchMxBillsMonth(serialNum);
			intMxPackageItems = moXieDataInfoMapper.searchPackageItems(serialNum);
			intMxPackageInfo = moXieDataInfoMapper.searchPackageInfo(serialNum);
			intMxUserBasicInfo = moXieDataInfoMapper.searchUserBasicInfo(serialNum);
			intMxAccountBaseInfo = moXieDataInfoMapper.searchAccountBaseInfo(serialNum);
			intMxDataSource = moXieDataInfoMapper.searchMxDataSource(serialNum);
			intMxBasicInfoCheckItems = moXieDataInfoMapper.searchBasicInfoCheckItems(serialNum);
			intMxCallNumTop3 = moXieDataInfoMapper.searchCallNumTop3(serialNum, dataType);
			intMxCallLocationTop3 = moXieDataInfoMapper.searchCallLocationTop3(serialNum, dataType);
			intMxCallContactDetail = moXieDataInfoMapper.searchCallContactDetail(serialNum);
			intMxRiskAnalysis = moXieDataInfoMapper.searchRiskAnalysis(serialNum);
			intMxRiskCheckItem = moXieDataInfoMapper.searchRiskCheckItem(serialNum);
			intMxActiveDegress = moXieDataInfoMapper.searchActiveDegress(serialNum);
			intMxConsumptionAnalysis = moXieDataInfoMapper.searchConsumptionAnalysis(serialNum);
			intMxCallAnalysis = moXieDataInfoMapper.searchMxCallAnalysis(serialNum);
			intMxCallDurationDetail = moXieDataInfoMapper.searchCallDurationDetail(serialNum, dataType);
			intMxCallLocationDetail = moXieDataInfoMapper.searchCallLocationDetail(serialNum, dataType);
			intMxCallTimeDetail = moXieDataInfoMapper.searchCallTimeDetail(serialNum);
			intMxCallThirdPartyDetail = moXieDataInfoMapper.searchCallThirdPartyDetail(serialNum);
			intMxCallFamilyDetail = moXieDataInfoMapper.searchCallFamilyDetail(serialNum);
			intMxActiveDegreeDetail = moXieDataInfoMapper.searchActiveDegreeDetail(serialNum);
			intMxConsumptionDetail = moXieDataInfoMapper.searchConsumptionDetail(serialNum);
			intMxCallLocal6m = moXieDataInfoMapper.searchCallLocal6m(serialNum);
			intMxCallMobile6m = moXieDataInfoMapper.searchCallMobile6m(serialNum);
			intMxCallNumTop6 = moXieDataInfoMapper.searchCallNumTop3(serialNum, dataTypeTwo);
			intMxCallLocationTop6 = moXieDataInfoMapper.searchCallLocationTop3(serialNum, dataTypeTwo);
			intMxCallDurationDetail6 = moXieDataInfoMapper.searchCallDurationDetail(serialNum, dataTypeTwo);
			intMxCallLocationDetail6 = moXieDataInfoMapper.searchCallLocationDetail(serialNum, dataTypeTwo);
		}
		dataMap.put("intMxDataUsageDetails", intMxDataUsageDetails);
		dataMap.put("intMxSmsDetails", intMxSmsDetails);
		dataMap.put("intMxUserInfo", intMxUserInfo);
		dataMap.put("intMxBillRecord", intMxBillRecord);
		dataMap.put("intMxLoanInfo", intMxLoanInfo);
		dataMap.put("intMxLoanRepayRecord", intMxLoanRepayRecord);
		dataMap.put("intMxCallDetails", intMxCallDetails);
		dataMap.put("intMxBillsMonth", intMxBillsMonth);
		dataMap.put("intMxPackageItems", intMxPackageItems);
		dataMap.put("intMxPackageInfo", intMxPackageInfo);
		dataMap.put("intMxUserBasicInfo", intMxUserBasicInfo);
		dataMap.put("intMxAccountBaseInfo", intMxAccountBaseInfo);
		dataMap.put("intMxDataSource", intMxDataSource);
		dataMap.put("intMxBasicInfoCheckItems", intMxBasicInfoCheckItems);
		dataMap.put("intMxCallNumTop3", intMxCallNumTop3);
		dataMap.put("intMxCallNumTop6", intMxCallNumTop6);
		dataMap.put("intMxCallLocationTop3", intMxCallLocationTop3);
		dataMap.put("intMxCallLocationTop6", intMxCallLocationTop6);
		dataMap.put("intMxCallContactDetail", intMxCallContactDetail);
		dataMap.put("intMxRiskAnalysis", intMxRiskAnalysis);
		dataMap.put("intMxRiskCheckItem", intMxRiskCheckItem);
		dataMap.put("intMxActiveDegress", intMxActiveDegress);
		dataMap.put("intMxConsumptionAnalysis", intMxConsumptionAnalysis);
		dataMap.put("intMxCallAnalysis", intMxCallAnalysis);
		dataMap.put("intMxCallDurationDetail3", intMxCallDurationDetail);
		dataMap.put("intMxCallDurationDetail6", intMxCallDurationDetail6);
		dataMap.put("intMxCallLocationDetail3", intMxCallLocationDetail);
		dataMap.put("intMxCallLocationDetail6", intMxCallLocationDetail6);
		dataMap.put("intMxCallTimeDetail", intMxCallTimeDetail);
		dataMap.put("intMxCallThirdPartyDetail", intMxCallThirdPartyDetail);
		dataMap.put("intMxCallFamilyDetail", intMxCallFamilyDetail);
		dataMap.put("intMxActiveDegreeDetail", intMxActiveDegreeDetail);
		dataMap.put("intMxConsumptionDetail", intMxConsumptionDetail);
		dataMap.put("intMxCallLocal6m", intMxCallLocal6m);
		dataMap.put("intMxCallMobile6m", intMxCallMobile6m);
		dataMap.put("intMxRechargeItems", intMxRechargeItems);
		MarvelsLogUtil.getInstance().info("魔蝎运营商数据组装结果 ： " + JSONUtil.toJsonStr(dataMap));
		long end = System.currentTimeMillis();
		MarvelsLogUtil.getInstance().info("魔蝎查询" + timeStr + "使用时间=[" + (end - start) + "]ms");
		return dataMap;
	}

	@Override
	public MoXieTaskResult runMoXieAlipayTask(String taskId, String loanId) {
		MoXieTaskResult moXieTaskResult = new MoXieTaskResult(); 
		moXieTaskResult.setResult(false);
		MarvelsLogUtil.getInstance().info("=============支付宝数据采集开始,loanId:" + loanId + ",taskId:" + taskId);
		try {
			MoxieTaskInfo info = moxieTaskInfoMapper.getMoxieTaskCurByParam(taskId, loanId, MoXieTaskType.ALIPAY.getType().toString());
			MarvelsLogUtil.getInstance().info("=============支付宝数据采集信息：" + com.alibaba.fastjson.JSONObject.toJSONString(info));
			
			//清除历史记录
			IntMxAlipayUserInfo userInfo = intMxAlipayUserInfoMapper.getMxAlipayUserInfo(loanId);
			if(userInfo != null){
				info.setResult("3");
				info.setUpdatedDate(new Date());
				moxieTaskInfoMapper.insertMoxieTaskInfoHistory(info);
				moxieTaskInfoMapper.deleteMoxieTaskInfo(info.getId());
				MarvelsLogUtil.getInstance().info("==========魔蝎支付宝任务历史数据清除：" + loanId);
				return moXieTaskResult;
			}
			
			//执行大于5分钟后将不再执行
			if(info.getUpdatedDate() != null && (info.getUpdatedDate().getTime() - info.getCreatedDate().getTime()) / 60000 >= 4){
				info.setResult("4");
				info.setUpdatedDate(new Date());
				moxieTaskInfoMapper.insertMoxieTaskInfoHistory(info);
				moxieTaskInfoMapper.deleteMoxieTaskInfo(info.getId());
				MarvelsLogUtil.getInstance().info("==========魔蝎支付宝任务获取超时，清除任务数据：" + loanId);
				return moXieTaskResult;
			}
			
			if(info != null){
				int i = moxieTaskInfoMapper.updateMoxieTaskInfo(info.getId(), "1");//先将状态改成认证中
				if(i > 0){
					String mobile = info.getMobile();
					String serial_num = SerialNumCreater.creater("MX", loanId);
					
					// 清除历史记录
					deleteDataQueryLogNew(mobile, ThirdMethodConstants.MX0007, "int_mx_data_query_log");
					deleteDataQueryLogNew(mobile, ThirdMethodConstants.MX0008, "int_mx_data_query_log");
					
					ApiResponse<MXAlipayReport> alipayResponse = this.alipayReportV6(mobile, taskId, serial_num, loanId, ThirdMethodConstants.channel);
					MarvelsLogUtil.getInstance().info("=============支付宝数据结果：" + com.alibaba.fastjson.JSONObject.toJSONString(alipayResponse));
					
					MarvelsLogUtil.getInstance().info("=============支付宝芝麻分数据采集开始,loanId:" + loanId + ",taskId:" + taskId);
					ApiResponse<MXAlipayZmsReport> zmsReportV2 = this.alipayZmsReportV2(mobile, taskId, serial_num, loanId, ThirdMethodConstants.channel);
					MarvelsLogUtil.getInstance().info("=============支付宝芝麻分数据结果：" + com.alibaba.fastjson.JSONObject.toJSONString(zmsReportV2));
					
					String result = "";// -3认证失败（请求失败） -2落库失败 -1认证失败（返回数据为空 ） 2认证成功
					if (alipayResponse.getCode() == RespStatus.SUCCESS.getCode()
							&& zmsReportV2.getCode() == RespStatus.SUCCESS.getCode()) {
						result = "2";
						moXieTaskResult.setResult(true);
						//记录芝麻分
						if(zmsReportV2 != null && zmsReportV2.getData() != null 
								&& zmsReportV2.getData().getMxAlipayZmsCores() != null
								&& zmsReportV2.getData().getMxAlipayZmsCores().size() >0){
							moXieTaskResult.setZmsCore(zmsReportV2.getData().getMxAlipayZmsCores().get(0).getZmScore());
						} 
						
						//记录花呗额度
						if(alipayResponse != null && alipayResponse.getData() != null
								&& alipayResponse.getData().getMxAlipayWealth() != null){
							BigDecimal huabaiLimit = new BigDecimal(alipayResponse.getData().getMxAlipayWealth().getHuabaiLimit());
							String huabaiLimitStr = huabaiLimit.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString();
							moXieTaskResult.setHuabaiLimit(huabaiLimitStr);
						}
					}

					if (alipayResponse.getCode() == RespStatus.NODATA.getCode()
							|| zmsReportV2.getCode() == RespStatus.NODATA.getCode()) {
						result = "-1";
					}

					if (alipayResponse.getCode() == RespStatus.DATABASE_ERROR.getCode()
							|| zmsReportV2.getCode() == RespStatus.DATABASE_ERROR.getCode()) {
						result = "-2";
					}

					if (alipayResponse.getCode() == RespStatus.REQ_ERROR.getCode()
							|| zmsReportV2.getCode() == RespStatus.REQ_ERROR.getCode()) {
						result = "-3";
					}
					if("2".equals(result)){
						//认证成功  插入历史记录表 删除原始表记录
						info.setResult(result);
						info.setUpdatedDate(new Date());
						moxieTaskInfoMapper.insertMoxieTaskInfoHistory(info);
						
						moxieTaskInfoMapper.deleteMoxieTaskInfo(info.getId());
					}else{
						//其他 则修改原始表状态
						moxieTaskInfoMapper.updateMoxieTaskInfo(info.getId(), result);
					}
				}
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("=============支付宝芝麻分数据采集异常,loanId:" + loanId + ",taskId:" + taskId, e);
		}
		return moXieTaskResult;
	}

	@Override
	public MoXieTaskResult runMoXieCarrierTask(String taskId, String loanId) {
		MoXieTaskResult moXieTaskResult = new MoXieTaskResult();
		moXieTaskResult.setResult(false);
		MarvelsLogUtil.getInstance().info("=============运营商数据采集开始,loanId:" + loanId + ",taskId:" + taskId);
		long start = System.currentTimeMillis();
		try {
			MoxieTaskInfo info = moxieTaskInfoMapper.getMoxieTaskCurByParam(taskId, loanId, MoXieTaskType.CARRIER.getType().toString());
			MarvelsLogUtil.getInstance().info("=============运营商数据采集信息：" + com.alibaba.fastjson.JSONObject.toJSONString(info));
			
			//清除历史老数据
			IntMxUserBasicInfo intMxUserBasicInfo  = intMxUserBasicInfoMapper.selectByLoanId(loanId);
			if(intMxUserBasicInfo != null){
				info.setResult("3");
				info.setUpdatedDate(new Date());
				moxieTaskInfoMapper.insertMoxieTaskInfoHistory(info);
				moxieTaskInfoMapper.deleteMoxieTaskInfo(info.getId());
				MarvelsLogUtil.getInstance().info("==========魔蝎运营商任务历史数据清除：" + loanId);
				return moXieTaskResult;
			}
			
			//执行大于5分钟后将不再执行
			if(info.getUpdatedDate() != null && (info.getUpdatedDate().getTime() - info.getCreatedDate().getTime()) / 60000 >= 5){
				info.setResult("4");
				info.setUpdatedDate(new Date());
				moxieTaskInfoMapper.insertMoxieTaskInfoHistory(info);
				moxieTaskInfoMapper.deleteMoxieTaskInfo(info.getId());
				MarvelsLogUtil.getInstance().info("==========魔蝎运营商任务获取超时，清除任务数据：" + loanId);
				return moXieTaskResult;
			}
			
			if(info != null){
				int i = moxieTaskInfoMapper.updateMoxieTaskInfo(info.getId(), "1");//先将状态改成认证中
				if(i > 0){
					String mobile = info.getMobile();
					
					// 清除历史记录
					deleteDataQueryLogNew(mobile, ThirdMethodConstants.MX0001, "int_mx_data_query_log");
					deleteDataQueryLogNew(mobile, ThirdMethodConstants.MX0002, "int_mx_data_query_log");
					deleteDataQueryLogNew(mobile, ThirdMethodConstants.MX0003, "int_mx_data_query_log");
					
					if (this.taskIdStatusIsFail(taskId)) {//如果任务已经不能查得数据 不需要再查询 将状态改成-3
						MarvelsLogUtil.getInstance().info("==========魔蝎运营商任务已经失败不需要再次查询,moxie--needn't query任务id：" + info.getTaskId());
						moxieTaskInfoMapper.updateMoxieTaskInfo(info.getId(), "-3");
						return moXieTaskResult;
					}
					MarvelsLogUtil.getInstance().info("=============>>>>运营商数据采集开始,moxie--need query,loanId:" + loanId + ",taskId:" + taskId + ",mobile" + mobile);
					Map<String, String> dataMap = new HashMap<String, String>();
					String serial_num = SerialNumCreater.creater("MX", loanId);
					ApiResponse apiResponseMobileReport = new ApiResponse();

					MarvelsLogUtil.getInstance().info("==================获取运营商用户报告请求开始,loanId:" + loanId + ",taskId:" + taskId);
					dataMap.put("task_id", taskId);
					apiResponseMobileReport = this.obtainUserMobileReport(dataMap, mobile, serial_num, loanId,
							ThirdMethodConstants.channel);
					MarvelsLogUtil.getInstance().info("==================获取运营商用户报告结果:" + apiResponseMobileReport.getMsg() + ",loanId:"
							+ loanId + ",taskId:" + taskId);

					ApiResponse apiResponseDataDetails = new ApiResponse();

					MarvelsLogUtil.getInstance().info("==================获取运营商全部数据开始:loanId:" + loanId + ",taskId:" + taskId);
					apiResponseDataDetails = this.obtainAllDataDetails(mobile, taskId, serial_num, loanId,
							ThirdMethodConstants.channel);
					MarvelsLogUtil.getInstance().info("==================获取运营商全部数据结果:" + apiResponseDataDetails.getMsg() + ",loanId:" + loanId
							+ ",taskId:" + taskId);


					ApiResponse apiResponseReportV2 = new ApiResponse();

					MarvelsLogUtil.getInstance().info("==================运营商查询用户报告v2开始,loanId:" + loanId + ",taskId:" + taskId);
					dataMap.put("task_id", taskId);
					apiResponseReportV2 = this.obtainUserMobileReportV2(dataMap, mobile, serial_num, loanId,
							ThirdMethodConstants.channel);
					MarvelsLogUtil.getInstance().info("==================运营商查询用户报告v2结果:" + apiResponseReportV2.getMsg() + ",loanId:" + loanId
							+ ",taskId:" + taskId);

					String result = "";// -3认证失败（请求失败） -2落库失败 -1认证失败（返回数据为空 ） 2认证成功
										// 1认证中
					if (apiResponseReportV2.getCode() == RespStatus.SUCCESS.getCode()
							&& apiResponseDataDetails.getCode() == RespStatus.SUCCESS.getCode()
							&& apiResponseMobileReport.getCode() == RespStatus.SUCCESS.getCode()) {
						result = "2";
						moXieTaskResult.setResult(true);
					}

					if (apiResponseReportV2.getCode() == RespStatus.NODATA.getCode()
							|| apiResponseDataDetails.getCode() == RespStatus.NODATA.getCode()
							|| apiResponseMobileReport.getCode() == RespStatus.NODATA.getCode()) {
						result = "-1";
					}

					if (apiResponseReportV2.getCode() == RespStatus.DATABASE_ERROR.getCode()
							|| apiResponseDataDetails.getCode() == RespStatus.DATABASE_ERROR.getCode()
							|| apiResponseMobileReport.getCode() == RespStatus.DATABASE_ERROR.getCode()) {
						result = "-2";
					}

					if (apiResponseReportV2.getCode() == RespStatus.REQ_ERROR.getCode()
							|| apiResponseDataDetails.getCode() == RespStatus.REQ_ERROR.getCode()
							|| apiResponseMobileReport.getCode() == RespStatus.REQ_ERROR.getCode()) {
						result = "-4";
					}

					if ("2".equals(result)) {
						// 认证成功 插入历史记录表 删除原始表记录
						info.setResult(result);
						info.setUpdatedDate(new Date());
						moxieTaskInfoMapper.insertMoxieTaskInfoHistory(info);

						moxieTaskInfoMapper.deleteMoxieTaskInfo(info.getId());
					} else {
						// 其他 则修改原始表状态
						moxieTaskInfoMapper.updateMoxieTaskInfo(info.getId(), result);
					}
					
				}
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("=============运营商数据采集异常,loanId:" + loanId + ",taskId:" + taskId, e);
		}
		MarvelsLogUtil.getInstance().info("#########################运营商查询总耗时（ms）：" + (System.currentTimeMillis() - start));
		return moXieTaskResult;
	}

	@Override
	public MXUserReportCall getReportMessage(String loanId, MoXieTaskType moXieTaskType) {
		MXUserReportCall mxUserReportCall = null;
		try {
			//先根据loanId 查询taskId（先查当前库，当前库没有则去历史库里面查找）
			String taskId = null;
			MoxieTaskInfo taskInfo = moxieTaskInfoMapper.getMoxieTaskCur(loanId, String.valueOf(moXieTaskType.getType()));
			if(taskInfo != null){
				taskId = taskInfo.getTaskId();
			}
			if(StrUtil.isEmpty(taskId)){
				taskInfo = moxieTaskInfoMapper.getMoxieTaskHis(loanId, String.valueOf(moXieTaskType.getType()));
				if(taskInfo != null){
					taskId = taskInfo.getTaskId();
				}
			}
			if(StrUtil.isEmpty(taskId)){
				MarvelsLogUtil.getInstance().info("getReportMessage - 魔蝎支付宝数据获取用户报告message信息,loan[" + loanId + "],taskId取不到诶");
				return mxUserReportCall;
			}
			MarvelsLogUtil.getInstance().info("getReportMessage - 魔蝎支付宝数据获取用户报告message信息,loan[" + loanId + "],taskId[" + taskId + "]");
			//组装请求
			String url = ThirdPropertiesInitUtil.getThirdProperties().getMx_baseUrl();
			MoxieApiFactory apiFactory = MoxieApiFactory.builder().withAuthToken(new AuthToken(ThirdPropertiesInitUtil.getThirdProperties().getMx_api_key(), ThirdPropertiesInitUtil.getThirdProperties().getMx_token()))
					.withBaseUrl(url).build();
			CarrierApi carrierApi = apiFactory.newApi(CarrierApi.class);
			//获取用户报告message
			MarvelsLogUtil.getInstance().info("getReportMessage - 魔蝎支付宝数据获取用户报告message信息,loan[" + loanId + "]");
			Response<MXUserReportCall> userReportCallResponse = carrierApi.getUserReportInfo(taskId, "report").execute();
			MarvelsLogUtil.getInstance().info("getReportMessage - 魔蝎支付宝数据用户报告message信息,loan[" + loanId + "],响应信息：" + com.alibaba.fastjson.JSONObject.toJSONString(userReportCallResponse));
			mxUserReportCall = userReportCallResponse.body();
			if(null != mxUserReportCall && mxUserReportCall.getResult()){
				if(moXieTaskType.getType() == 1){
					//写入运营商表
					IntMxUserBasicInfo intMxUserBasicInfo  = intMxUserBasicInfoMapper.selectByLoanId(loanId);
					if(intMxUserBasicInfo != null){
						intMxUserBasicInfo.setMessage(mxUserReportCall.getMessage());
						intMxUserBasicInfoMapper.updateByPrimaryKeySelective(intMxUserBasicInfo);
					}
				}else if(moXieTaskType.getType() == 3){
					//写入支付宝表
					IntMxAlipayUserInfo userInfo = intMxAlipayUserInfoMapper.getMxAlipayUserInfo(loanId);
					if(userInfo != null){
						userInfo.setMessage(mxUserReportCall.getMessage());
						intMxAlipayUserInfoMapper.updateByPrimaryKeySelective(userInfo);
					}
				}
			}
			MarvelsLogUtil.getInstance().info("getReportMessage - 魔蝎支付宝数据获取用户报告message信息完成,loan[" + loanId + "]");
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("getReportMessage - 魔蝎支付宝数据获取用户报告message信息异常,loan[" + loanId + "]", e);
		}
		return mxUserReportCall;
	}

	@Override
	public List<MoxieTaskInfo> selectMoxieTaskInfo(String type) {
		return moxieTaskInfoMapper.selectMoxieTaskInfo(type);
	}

	@Override
	public int updateMoxieProcessing() {
		return moxieTaskInfoMapper.updateMoxieProcessing();
	}
	
	

}
